我有一份准备好的声明,可以生成价格清单。价格由项目的价值乘以数量确定。
if ($select = $db -> prepare("SELECT value, quantity FROM items"))
{
$select -> execute();
$select -> bind_result($value, $quantity);
while ($select -> fetch())
{
$subtotal = $value * $quantity;
echo $subtotal.'<br />';
}
$select -> close();
}
// I want to put the $total here.
这会输出一个数字列表:
100
50
200
1.50
我想以某种方式将每个$ subtotal加起来并将它们放入我准备好的语句之外的另一个变量“$ total”中。这可以在查询中不做数学吗?
答案 0 :(得分:5)
在预准备语句之外声明变量$total = 0
,并在while()
循环中使用它来计算总价值,如下所示:
$total = 0;
if ($select = $db -> prepare("SELECT value, quantity FROM items")){
$select->execute();
$select->bind_result($value, $quantity);
while($select -> fetch()){
$subtotal = $value * $quantity;
$total += $subtotal;
}
$select->close();
}
echo $total;
旁注:正如@ Fred-ii和@JuanTomas所提到的,由于您使用的是没有任何占位符的预准备语句,因此您可以将->prepare()
更改为->query()
在完全删除->execute()
声明的同时,它对您的代码没有任何影响。