我的 php 代码中的未定义变量错误

Error of undefined variable in my php code

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

count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\moed\cart.php on line 57

$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;
    }
}

你的代码完全乱七八糟。

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

抓取时,需要使用$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);
}