firtman / php-fundamentals

4 stars 9 forks source link

PHP Code on the Cryptomasters does not evaluate the variables $amount and $crypto and they are printed as literal text #2

Open techwithtwin opened 1 month ago

techwithtwin commented 1 month ago

` <?php

// Superglobal variables
$amount = $_POST["amount"];
$crypto = $_POST["crypto"];

if (isset($amount) && isset($crypto)) { ?>

    <p>You want to convert $amount from $crypto.</p>

    <?php
} else { ?>
    <h2>Something went wrong</h2>

<?php } ?>

`

The P tag <p>you want to convert $amount from $crypto </p> does not evaluate, and is treated as literal text

techwithtwin commented 1 month ago

image

JelenaMarjanovic commented 1 month ago

You can fix the line containing the paragraph by changing it to: <p>You want to convert <?php echo $amount; ?> from <?php echo $crypto; ?>.</p> Or you can use the shorthand syntax as shown by Maxi: <p>You want to convert <?= $amount ?> from <?= $crypto ?>.</p>

In PHP, you cannot directly evaluate variables inside a literal string like: "<p>You want to convert $amount from $crypto.</p>" because it treats the text as a single literal string. Instead, you need to use PHP tags (<?php ... ?>) to embed the variables in the HTML, as shown above. Avoid using single quotes (') for interpolation, as they do not parse variables within the string.