使用while循环从PHP中的SQL数组中获取值


Grab values from SQL array in PHP with while loop

所以我在mySQL中有一个表,它保存有customerID、productPrice和数量的销售记录。我需要从每一行中获取成本,然后将其编译为totalCost。我需要使用while循环(分配指令)来做到这一点,到目前为止我还没有任何运气。这就是我现在的位置,任何帮助都感谢

while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $productPrice * $quantity
    $totalCost = $totalCost + $cost
};
echo "$totalCost";
$totalCost = 0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $record["productPrice"] * $record["quantity"];
    $totalCost += $cost;
}
echo "$totalCost";

这更像是一个注释,但还不够酷,不能写一个,请尝试将$totalcost变量放在while循环之外,这样它的值就不会被每次迭代覆盖。

$totalcost=0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
$cost = $record['productPrice'] * $record['quantity'];
$totalCost = $totalCost + $cost;
};
$totalCost = 0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $record['productPrice'] * $record['quantity'];
    $totalCost += $cost
}
echo "$totalCost";

你首先需要声明$totalCost,否则你会得到一个未定义的错误,在结束它们时不需要在花括号中添加分号,而且当你使用$record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)提取信息时,你需要将信息作为数组键访问,这样价格就会是$record['price']

更改

$cost = $productPrice * $quantity

进入

$cost = $record["productPrice"] * $record["quantity"];