简体   繁体   中英

Echoing a link containing php

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>

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

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

echo sprintf('<td><a href="?action=addToCart&product=%s">Add To Cart</a></td>', $key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM