0

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?

2
  • What is the exact HTML being rendered by this code? Commented Nov 9, 2017 at 13:57
  • I got it fixed, turns out the $id variable was in the wrong place. Thanks though. Commented Nov 9, 2017 at 14:00

2 Answers 2

2

You're ending the href attribute too early.

<a href=\"seller.php?id=".$id."\">

This will put the $id inside the href attribute, where it belongs.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! I didn't know that you could put variables inside quotes, I thought you had to keep them in their own seperate section. I will vote yours as best answer as soon as I can.
The varaiable's outside the quote (that's what the ".$id." is doing). It's the escaped quote afterwards that's causing the problem. If we say $id=50, the end result before would look like <a href="/seller?id="50>. It's only the part inside the output quotes that forms your link. Moving the escaped quote so it sits at the end of the tag means it will include the $id value.
0

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.