Zils
Zils

Reputation: 405

PHP SQL Keep adding row['value'] with previous inside loop

here is my code-

$sql="SELECT * FROM payment WHERE customerid='$id'";
if ($result=mysqli_query($con,$sql))
  {
  while ($row=mysqli_fetch_assoc($result);
    {
    echo $row['fraction_payment'];
    }    
}

What im trying to do: constantly keep adding $row['fraction_payment'] with the previous value.

if database value of

fraction_payment 1 = 100 
fraction_payment 2 = 200 
fraction_payment 3 = 300

expected result will be:

$row['fraction_payment'][1] = 100
$row['fraction_payment'][2] = 300
$row['fraction_payment'][3] = 600

How should i proceed to do that in PHP?

Upvotes: 0

Views: 24

Answers (2)

r.1
r.1

Reputation: 101

$sql="SELECT * FROM payment WHERE customerid='$id'";
if ($result = mysqli_query($con,$sql))
{
  $sum = 0;
  $result = [];
  while ($row = mysqli_fetch_assoc($result);
  {
    $sum += $row['fraction_payment'];
    $result[] = $sum;
  }
  var_dump($result);
}

And don't forget about SQL injections: How can I prevent SQL injection in PHP?

Upvotes: 1

delboy1978uk
delboy1978uk

Reputation: 12375

This should do the trick, pretty self explanatory:

$total = 0;
$sql="SELECT * FROM payment WHERE customerid='$id'";
if ($result=mysqli_query($con,$sql))
{
  while ($row=mysqli_fetch_assoc($result);
  {
    $total += $row['fraction_payment'];
    echo $total;
  }    
}

Upvotes: 1

Related Questions