我正在尝试搭建一个网店(这是一个项目),购物车使用的是数据库,我会根据用户信息获取相应的信息并打印。但是我的 while 循环只能找到最后一个商品而不能找到其他两个。现在我很确定旧数据被覆盖了,因此不会被打印出来,但我不知道该如何解决这个问题。
以下是我目前的代码:
<?php
if(isset($_SESSION['userid'])){
$db = new PDO('mysql:host=localhost;dbname=ismsite', 'root', 'e-scooter');
$result = $db->prepare("SELECT * FROM cart where user_id=:userid ORDER BY cart_id DESC LIMIT 3 ");
$result->bindParam(':userid', $_SESSION['userid']);
$result->execute();
$info = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$pid = $row['product_id'];
$quantity = $row['quantity'];
$result = $db->prepare("SELECT * FROM Products WHERE productID=:pid");
$result->bindParam(':pid', $pid);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo $row['naam'];
}
}
}
else{
echo "Je moet inloggen om te kunnen winkelen.";
}
?>
有人能帮我解决这个问题吗?
$row
和$result
这两个变量名,导致内部循环中的值会覆盖外部循环中的值......这很可能会出现问题......如果你必须要嵌套循环,那么至少对于$result
这个变量名,应该使用不同的变量名。 - Mark Bakerecho $row['naam']
,并查看您获得的结果。SELECT c.*,p.* FROM cart c INNER JOIN Products p ON p.product_id = c.product_id where user_id=:userid ORDER BY cart_id DESC LIMIT 3
我假设product_id是两个表中的字段。 - ArtleMaks