1
<?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>";

     ?>

but the result say

<br>

Notice: Undefined variable: sum in C:\xampp\htdocs\work_shop\back_end\data_input_output\result.php on line 57

<br>

total cost of this month is $300 which is correct result....

<br>

How can I solve this problem...??

1
  • define $sum before loop. Commented Jun 5, 2015 at 10:36

2 Answers 2

3

You need to define $sum variable outside loop. Try this-

<?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>";

?>
Sign up to request clarification or add additional context in comments.

Comments

3

$sum is undefined because you are only adding, and not setting a value.

<?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>';
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.