Reputation: 45
I am building a ecommerce site. Trying to create a product-details
page where when clicking on a button it give me details of just that item. Database already created and connected but keep getting all items when clicking on one item instead of just the one I clicked on. Can I do it by id
?
Here is my details.php code
<?php
$con = mysqli_connect('localhost','root');
mysqli_select_db($con, 'Test');
$sql = "SELECT * FROM products WHERE featured=1";
$featured = $con->query($sql); ?>
<div class="col"> <div class="col-md-8">
<div class="row">
<h2 class="text-center">Product Details</h2>
<?php
while($product =mysqli_fetch_assoc($featured)):
?>
<div class="col-md-5">
<h4> <?= $product['title'];?></h4>
<img src="<?= $product['images'];?>" height="200px" width="300px" alt="<?=
$product['title']; ?>" />
<p class="price">Price: <?= $product['price'];?></p>
<p class="desc">Description: <?= $product['description'];?></p>
<p class="bname">Brandname: <?= $product['brandname'];?></p>
</div>
<?php endwhile; ?>
</div>
</div>
Upvotes: 0
Views: 1828
Reputation: 8043
Remove the while block (you only need to retrieve one record)
change the query to something like select * from [table] where id=?
bind the id parameter and execute the prepared statement
Hence, Please change your code to :
<?php
$con = mysqli_connect('localhost','root');
mysqli_select_db($con, 'Test');
$sql = "SELECT * FROM products WHERE featured=1 and id=?";
$stmt=mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'i',$_GET["id"]);
mysqli_stmt_execute($stmt);
$featured = mysqli_stmt_get_result($stmt);
?>
<div class="col"> <div class="col-md-8">
<div class="row">
<h2 class="text-center">Product Details</h2>
<?php
$product =mysqli_fetch_assoc($featured);
// while($product =mysqli_fetch_assoc($featured)):
?>
<div class="col-md-5">
<h4> <?= $product['title'];?></h4>
<img src="<?= $product['images'];?>" height="200px" width="300px" alt="<?=
$product['title']; ?>" />
<p class="price">Price: <?= $product['price'];?></p>
<p class="desc">Description: <?= $product['description'];?></p>
<p class="bname">Brandname: <?= $product['brandname'];?></p>
</div>
<?php
//endwhile;
?>
</div>
</div>
Now just call the PHP (say thru a hyperlink) by details.php?id=xxxx
For example , if you want to retrieve the record of id=10, then visit details.php?id=10
Upvotes: 1