dannstuff dannstuff - 5 months ago 5x
HTML Question

Concatenating an integer based on an sql id for use in a html ID tag

I am currently building a website as part of my course. The website is an eCommerce site. I am storing the products in an SQL database, then echoing each row out into a table using a php script. I have managed to do this fine, however, I now wish to add a button on each product that will contain a href which adds that chosen product to a cart. The only problem is, to build the cart array I need the ID, and to set the ID in the loop you have to concatenate an integer, and I do not know how to do this in my script, here is what I currently have, any help would be much appreciated.

while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td><br>".$row['Name']."</td><br>";
echo "<br>";
echo "<td><img src=".$row['Image']."height='200' width = '200'"."</td><br>";
echo "<br>";
echo "<td>Price: £".$row['Price']."</td><br>";
echo "<button type='button'><a href='test.php' id=>Buy</a></button>";
echo "</tr>";


Thanks in advance, I hope I have given enough detail.


There are a few ways to go about this.

$id = 123; // as an example. Use the appropriate variable for this.

echo "<button type='button'><a href='test.php' id=$id>Buy</a></button>";

echo "<br>";

echo "<button type='button'><a href='test.php' id=\"$id\">Buy</a></button>";

Which in HTML source reveals:

<button type='button'><a href='test.php' id=123>Buy</a></button><br><button type='button'>

<a href='test.php' id="123">Buy</a></button>

Depending on if you want them quoted or not, if that's what the question is about.


echo "<button type='button'><a href='test.php' id='".$id."'>Buy</a></button>";

with HTML source revealing:

<button type='button'><a href='test.php' id='123'>Buy</a></button>

Then you can pull the data with a GET array.


$var = $_GET['id'];


echo "<button type='button'><a href='test.php?id=".$id."'>Buy</a></button>";

HTML source:

<button type='button'><a href='test.php?id=123'>Buy</a></button>

In your while loop, you could assign a variable to the id.


$id = $row['id'];

I must note that using single quotes could have adverse effects if your data contains single quotes, so it's best to use double quotes.

I.e.: (and escaping double quotes)

echo "<button type=\"button\"><a href=\"test.php?id=".$id."\">Buy</a></button>";

Producing this in HTML source:

<button type="button"><a href="test.php?id=123">Buy</a></button>

I had first hand experience with this last week actually, where HTML source revealed warnings about malformed HTML markup with data such as Mark's Bar & Grill.

while ($row = mysqli_fetch_assoc($result)){

    $id = $row['id']; // assuming you have a row for id.

    // all your other code

    echo "<button type='button'><a href='test.php?id=".$id."'>Buy</a></button>";


This would be related to your other row for the name $row['Name'] etc.

Be careful with that.