-1

我是 php 新手,我正在尝试从我的数据库产品表中获取产品名称并将该数据存储到 $product 数组中。我收到错误

count():参数必须是数组或对象,在 C:\xampp\htdocs\moed\cart.php 第 57 行实现 Countable

$sqlprod = "SELECT pname FROM products limit 10";
$sqlprice = "SELECT price FROM products limit 10";
$result = $conn->query($sqlprod);
$result1 = $conn->query($sqlprice);

if ($result->num_rows And $result1->num_rows > 0) {
    $products = array();
    $amounts = array();
    while($row = mysql_fetch_assoc($sqlprod)){
        $products[] = $row; 
    }
    while($row1 = mysql_fetch_assoc($sqlprice)){
        // add each row returned into an array
        $products[] = $row1;
    }
} 

// I am getting error of undefined variable products at the for loop below 
if ( !isset($_SESSION["total"]) ) {
    $_SESSION["total"] = 0;
    for ($i=0; $i< count($products); $i++) {
        $_SESSION["qty"][$i] = 0;
        $_SESSION["amounts"][$i] = 0;
    }
}
4

1 回答 1

0

你的代码完全搞砸了。

不需要多个查询,只需执行一个获取两列的查询。如果需要,您仍然可以将每一列保存在单独的数组中。

当您获取时,您需要使用$result,而不是$sqlprod

由于您使用的是mysqli扩展程序,因此您需要使用mysqli_fetch_assoc(),而不是mysql_fetch_assoc(). 但是由于您使用的是 OO 样式,因此最好使用$result->fetch_assoc().

你把价格放进去$products,不是$amounts

您不需要循环来多次创建具有相同元素的数组,您可以使用array_fill()它。

$sqlprod = "SELECT pname, price FROM products limit 10";
$result = $conn->query($sqlprod);

$products = array();
$amounts = array();
while($row = $result->fetch_assoc()){
    $products[] = $row['pname'];
    $amounts[] = $row['price'];
}

if ( !isset($_SESSION["total"]) ) {
    $_SESSION["total"] = 0;
    $_SESSION['qty'] = $_SESSION['amounts'] = array_fill(0, count($products), 0);
}
于 2018-03-29T17:44:12.007 回答