dhani
dhani

Reputation: 127

Query database on clicking a link

I'm retrieving products from my database and listing them in a while loop. Like this

<?php
  while($row = mysql_fetch_row($result)){
    echo '<div class="product_info">';
     echo '<div class="category_product_title"><a href="category-page.php">Product</a>';
     echo '</div>';
      echo '<div   class="category_product_number">#'.$row[0].'('.$row[1].')'.'</div>';//prints id and name
     echo '<div class="category_product_description">'.$row[2].'</div>';//prints description
     echo '<div class="category_product_price">'.$row[4].'TL</div>';//prints price
      echo '<div class="category_details"><a href="productpage2.php">DETAILS</a></div>';//The link to   list the product details
    echo '</div>';
    echo '</div>';
 }
?>

I want to be able to print more details on a paticular prodcut when the "DETAILS" link is clicked by getting the id or name of that paticular product and using to query the database. I tried saving the id in a session variable like this $_SESSION['id'] = $row[0] but since i'm looping through these products, i'm not able to get the id of a specific product when it is clicked. How can i do this?. I'm confused because of the loop. Thanks

Upvotes: 0

Views: 266

Answers (2)

Oliver Nagy
Oliver Nagy

Reputation: 336

You can assign a different link to each one of the products with a GET variable.
Instead of <a href="productpage2.php">DETAILS</a>, the link could point to <a href="productpage2.php?id='.$row[0].'">DETAILS</a>.

Then, on the product page productpage2.php, you can get the selected ID from the $_GET superglobal array like this:

$id = $_GET['id'];

Upvotes: 2

user428517
user428517

Reputation: 4193

Lots of ways to do this. I would probably do something like:

echo '<div class="product_info" data-product-number="' . $row[0] . '">';

Then just grab the data-product-number attribute with JavaScript and pass it along with the request. Obviously, you'll need to verify this on the server side somehow once the request is made, since a user could set the product number in the request to anything they'd like.

Upvotes: 0

Related Questions