首页 > 解决方案 > 在查找数组数据上实现的 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();
    }
 }

标签: phpmysql

解决方案


首先,您的代码有拼写错误(在参数 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);
    }

推荐阅读