1

As an example I have four input text boxes in a form. I am trying to calculate the cost of each item type (quantity * cost) and the compute a total of all items. I have placed the formula inside a while loop to calculate cost of all the possible items found in the form. I am not receiving any result in return for the total cost? Demo

php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
      $discount = $_POST['discount'];
      $i = 1;
      while(isset($_POST['quantity'.$i])){
          $quantity = $_POST['quantity'.$i];
          $cost = $_POST['cost'.$i];
          $total = $quantity * $cost;
          $i++;
      }

}

html

<div id="contact-area">
  <form action="" method="post">
    <label>Quantity:</label> <input type="text" name="quantity1" id="quantity1"> <label>Cost:</label><input type="text" name="cost1" id="cost1"><br /><br />
    <label>Quantity:</label> <input type="text" name="quantity2" id="quantity2"> <label>Cost:</label><input type="text" name="cost2" id="cost2"><br /><br />
  <br /><br />
  <input type="submit" value="Submit" >
  </form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
  echo"<p>Amount Due: $". $total ."</p>";
}
?>
</div>

5 Answers 5

3

You're re-assigning $total instead of adding to it, so the final total will just be from the last item. It should be:

$total += $quantity * $cost;
       ^
Sign up to request clarification or add additional context in comments.

Comments

1

Your $total variable is being over-written every loop.

It should be:

$total += ($quantity * $cost);

Comments

1

You need to add

$total = 0;

before while loop and in loop change

$total = $quantity * $cost;

to

$total += $quantity * $cost;

Comments

1

Try this:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
  $discount = $_POST['discount'];
  $i = 1;
  $total = 0;
  while(isset($_POST['quantity'.$i])){
      $quantity = $_POST['quantity'.$i];
      $cost = $_POST['cost'.$i];
      $total += $quantity * $cost;
      $i++;
  }

}

Comments

0

Rewriting your code like this will resolve the issue:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
      $discount = $_POST['discount'];
      $i = 1;
      $total = 0;
      while(isset($_POST['quantity'.$i])){
          $total += $_POST['quantity'.$i] * $_POST['cost'.$i];
          $i++;
      }

}

This is what was changed:

  • Adding a $total = 0; before the while loop to ensure that variable is assigned no matter what.
  • Removing the $quantity = $_POST['quantity'.$i]; & $cost = $_POST['cost'.$i]; since those are superfluous duplications of values that can be accessed directly.
  • Changing $total = to $total += so the $total is actually accumulated in the variable.

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.