php - 在查找数组数据上实现的 Foreach 只找到一个数据
问题描述
我在一个函数中使用了两个查询。查找数据数组的第一个查询。第二个查询是根据检查第一个查询中的数组数据来选择行。但是整个函数只返回一行数据。
function getCartItems($conn)
{
$cust_id=$_SESSION['cust_id'];
$stmtSelect1 = $conn->prepare("SELECT product_id FROM tbl_cart WHERE cust_id=cust_id");
$stmtSelect1->bindParam('cust_id',$cust_id);
$stmtSelect1->execute();
$product_id= $stmtSelect1->fetchAll();
foreach($product_id as $productid) {
$stmtfetch = $conn->prepare("SELECT * FROM tbl_item WHERE product_id=:products_id");
$stmtfetch->bindParam(':products_id',$productid['product_id']);
$stmtfetch->execute();
$datas = $stmtfetch->fetchAll();
print_r($datas);
exit();
}
}
解决方案
首先,您的代码有拼写错误(在参数 product_id/products_id 之前缺少“:”)。
这应该有效:
$cust_id=$_SESSION['cust_id'];
$stmt = $conn->prepare("SELECT tbl_item.* FROM tbl_cart, tbl_item WHERE tbl_cart.cust_id = :cust_id AND tbl_item.product_id = tbl_cart.product_id);
$stmt->bindParam('cust_id',$cust_id);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
print_r($row);
}
推荐阅读
- python - 为什么 time.sleep() 准确性受 Chrome 影响?
- gis - 使用 ArcGIS API for JavaScript 以 3D 方式堆叠拉伸多边形
- ios - ios模拟器构建工作,但真实设备构建失败
- excel - excel中的高级格式化
- python - 无法访问我的 kivy 类中的对象,无法使用“app.root”和“self.ids”
- dpdk - 与 Intel X710 NIC 兼容的 DPDK 驱动程序
- java - 使用avro序列化将整个Json发送到kafka?
- javascript - 使用firebase的服务器时间戳
- java - JavaFX:与窗口大小相关的性能
- c++ - 当我在条件语句中使用相同的值时,为什么我的插入排序算法返回不同的值?