<?php
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo "<h2> total cost of this month is $".$sum. "</h2>";
?>
但结果说
<br>
注意:未定义的变量:总和 C:\ xampp \ htdocs \ work_shop \ back_end \ data_input_output \ result.php on 第57行
<br>
本月总费用为$300
这是正确的结果......
<br>
我该如何解决这个问题...... ??
答案 0 :(得分:3)
$ sum未定义,因为您只是添加,而不是设置值。
<?php
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
$sum = 0;
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo '<h2> total cost of this month is $'.$sum.'</h2>';
?>
答案 1 :(得分:3)
您需要在外部循环中定义$sum
变量。试试这个 -
<?php
$sum = 0; // define sum outside loop
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo "<h2> total cost of this month is $".$sum. "</h2>";
?>