[英]How to fetch data from database individually in php
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.尝试创建一个
product-details
页面,当点击一个按钮时,它会给我提供该项目的详细信息。 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
?我可以通过
id
来做吗?
Here is my details.php code这是我的详细信息。php代码
<?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>
Remove the while block (you only need to retrieve one record)去掉 while 块(只需要检索一条记录)
change the query to something like select * from [table] where id=?
将查询更改为
select * from [table] where id=?
bind the id parameter and execute the prepared statement绑定id参数,执行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现在只需通过 details.php?id=xxxx 调用 PHP(通过超链接说)
For example, if you want to retrieve the record of id=10, then visit details.php?id=10比如要检索id=10的记录,那么访问details.php?id=10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.