0

I was wondering is it possible to echo out a link that also contains php? It will be a link to add items to a cart.

I suspect I may have missed quotations or simply structured the link wrong.

<table>
<tr>
<th>SKU</th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php foreach ($products as $key => $product) {
echo '<tr>';
echo '<td>' . $product['SKU'] . '</td>';
echo '<td>' . $product['name'] . '</td>';
echo '<td>' . '&pound;'. number_format($product['Price'],2) . '</td>';
echo '<td>' . <a href="?action=addToCart&product=<?php echo $key; ?>">Add To Cart </a> . '</td>';
echo '</tr>';
}
?>
</table>
WibblyWobbly
  • 145
  • 3
  • 7
  • 18

3 Answers3

4

You're already in a PHP block, so you don't need to use the php tags again. Just use this instead:

echo '<td><a href="?action=addToCart&product='.$key.'">Add To Cart</a></td>';

To switch to the double-quotes so that the variable will be processed inline (like I mentioned in the comment), you can change the line to this:

echo "<td><a href='?action=addToCart&product=$key'>Add To Cart</a></td>";
aynber
  • 22,380
  • 8
  • 50
  • 63
  • Thankyou so much! I've been banging my head against a wall to figure this out! One last question, do the same rules apply for the other table datas? I can remove the single quotes around each tag? – WibblyWobbly Jun 12 '13 at 17:42
  • Yes, as long as you're in the middle of an html block, you don't need to break it apart. The only time you need to use the single quotes to get back out of it is when you're adding a PHP variable. If you switch the quotes around, double-quotes to enclose the echo and single-quotes inside of the HTML, then you don't even need to do that. The echo will process the PHP in-line. I'll edit my answer to show what I mean. – aynber Jun 12 '13 at 17:49
1

please read the manuel how to quoate a string in php and what is the difference between single and double quates

to your problem:

echo '<td><a href="?action=addToCart&product=.'$key.'">Add To Cart </a></td>';

or in double quotes:

echo "<td><a href=\"?action=addToCart&product={$key}\">Add To Cart </a></td>";

but keep in mind quoting should be one of the basics to handle correct with a language

donald123
  • 5,638
  • 3
  • 26
  • 23
0
echo sprintf('<td><a href="?action=addToCart&product=%s">Add To Cart</a></td>', $key);
phpisuber01
  • 7,585
  • 3
  • 22
  • 26
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 06:42