Search code examples
phpquoting

php echo quotation marks error


I'm having hard time with quotation marks. I have this line of code;

echo "<a href='$bName'_read.php?bid='$bid'&id='$next_id[id]'>NEXT</a>";

with 3 variables, $bName,$bid, and $next_id[id].

There is something wrong with the quotations I've used. I also tried this;

echo "<a href='".$bName."_read.php?bid=".$bid."&id=".$next_id['id']."'">";

but it's still not working.

Can anyone explain how quoting works in this case please?


Solution

  • You don't need to put single quotes around every PHP variable. It should make sense in HTML instead, for example;

    echo "<a href='{$bName}_read.php?bid={$bid}&amp;id={$next_id['id']}'>NEXT</a>";
    

    You need curly braces ({}) around object and array variables, but it is also useful for normal variables. Also, the array index should be in quotes as it is a string (not required for integer indexes).

    Additionally, I changed the ampersand (&) to &amp; as & signifies the start of a special character code (just like &amp;), so although in this case it wouldn't be a problem it is best practice to put the HTML char code in, even in a URL.