PHP echo returning blank value

Zach Zwerling asked
php
via

So I am trying to link using data I got from a function but it keeps giving me a blank value for ID. Here’s my code for what I’m trying to print

 <h3 style="text-align: center;">Seller: <?php $sellername = 
getNameFromListingID(); $id = getIDByUsername($sellername); echo "<a href="seller.php?id="".$id.">".$sellername."</a>";?></h3>

The functions work properly, I have tried printing both of them and it works. They’re in a file called getinfo.php, which I have

Include 'getinfo.php';

At the top of my document.

The link with the name works but I always get seller.php?id=, with no value after. Any clue as to why?


Answer
via

Use single quotes in PHP, it’s a good practice to get into, and it’s also slightly (a teeny tiny bit) faster for PHP to process. Why? Because, when you use double quotes, you’re telling PHP that your string contains variables that may need to be evaluated.

So in truth, you don’t even need the quotes around variables here.

echo "<a href="seller.php?id=$id">$sellername</a>";

But doing it like this would be following a best practice.
And now you don’t need to escape " double quotes that HTML uses.

echo '<a href="seller.php?id='.$id.'">'.$sellername.'</a>';

Caution: It’s also a very good idea to escape special characters in anything you’re outputting into HTML markup. That avoids the potential for an XSS vulnerability. See: htmlspecialchars()

echo '<a href="seller.php?id='.htmlspecialchars($id).'">'.htmlspecialchars($sellername).'</a>';
Share This
Posted in: