为什么它不能填充整个产品列表

时间:2014-01-16 11:09:01

标签: php

我不知道我的代码有什么问题。 supposingly, 它应该填充我在我的数据库中的所有项目(id) 然而, 它只是告诉我我的数据库中有多少项目,而不是列出我在数据库中的所有产品ID

有人可以帮助指出我的错误吗? 我正在关注youtube制作购物车的教程。

<?php
$product_list = "";
$sql = mysql_query("SELECT * FROM supermarket");
$productCount = mysql_num_rows($sql);//count output amount
if($productCount > 0){
    while($row = mysql_fetch_array($sql)){
        $id = $row["id"];
        $product_list = "$id<br>";
    }
}
else{
    $product_list = "You have no products listed in your store yet";
}
?>

3 个答案:

答案 0 :(得分:4)

您正在覆盖$product_list变量。相反,你需要在数组变量

中获取所有id
$product_list = array();
if($productCount > 0){
    while($row = mysql_fetch_array($sql)){
        $id = $row["id"];
        $product_list[] = $id;
    }
}
print_r($product_list);

注意: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

答案 1 :(得分:1)

每次绕过while循环,您都会覆盖$product_list的先前内容。您可能希望使用.=运算符进行连接,如下所示:

while($row = mysql_fetch_array($sql)){
    $id = $row["id"];
    $product_list .= "$id<br>";
}

我假设您稍后输出$product_list(循环后的某个时间),例如:

echo $product_list;

答案 2 :(得分:0)

如果您需要产品中的所有数据:

$product_list = array();
  if($productCount > 0){
  while($row = mysql_fetch_array($sql)){
    $id = $row["id"];
    $product_list[$id] = $row;
  }
}
print_r($product_list);

你必须将它存储在一个数组中,你会在while循环的每个序列中覆盖$ product_list 它不是你得到的计数顺便说一句,它的最后一个id是你在代码中返回的