我有一个从中提取数据的数据库。在我原来的 PHP 脚本上,我运行查询并获取数据,然后将其回显,但由于某种原因,我拥有的第二个脚本无法正常工作。每个页面上的查询都是相同的,所以我不确定为什么要告诉我这个,但它说我的 $price
变量未定义。
这是无法正常工作的代码:
$cartoutput = "";
$cartTotal="";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<font>Your Cart is currently empty.</font>";
}else{
$i=0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$item_id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
while ($row = mysqli_fetch_array($result)) {
$product_name = $row["name"];
$price = $row["price"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$i++;
$cartoutput .="<font>Item $i - </font>"; $cartoutput .= $each_item['item_id'] . $each_item['quantity'] . "<br />";
}
}
?>
更具体地说,行:
$pricetotal = $price * $each_item['quantity'];
是导致问题的原因。正如我之前所说,我有另一个以相同方式使用的 PHP 脚本,并且没有给我任何问题。 $price
是不是定义在 WHILE 循环中?我试过用不同的方式编码,但没有任何效果。我的最终目标是只回显$cartTotal
,但我不能这样做,因为我收到错误 $price is not defined?
最佳答案
$price
是在 while 循环中定义的,因此它的上下文在 while 循环中结束。在您尝试使用它时,它已不存在。即使允许这样做,您也只能读取 $price
的最后一个值。您想在循环中进行整个计算。将其更改为:
while ($row = mysqli_fetch_array($result)) {
$product_name = $row["name"];
$price = $row["price"];
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$i++;
$cartoutput .="<font>Item $i - </font>"; $cartoutput .= $each_item['item_id'] . $each_item['quantity'] . "<br />";
}
关于php - 使用 MySQL 和 PHP 为我的电子商务网站显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983119/