<?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>
注意:未定义变量:sum inC: xampp 根 work_shop back_end data_input_output result.php线57
<br>
本月总费用为$300
哪个是正确的结果....
<br>
我怎样才能解决这个问题?? 需要在循环外定义$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>";
?>
$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>';
?>