Igor Minascurta
Igor Minascurta

Reputation: 75

How to calculate the sum of variables in PHP

It calculates, but starting from the second row.

<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query); 
$row = mysql_fetch_array($result);
$sold= array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
  $sold=$row['contract']+$row['tva'];
  echo "<table><tr><td>" . $sold. "</td></tr></table>";
}
?>

Upvotes: 0

Views: 2353

Answers (3)

fantaghirocco
fantaghirocco

Reputation: 4878

Your code has many issues:

  1. Your code starts to calculate from the second row because of the line:

    $row = mysql_fetch_array($result);
    

    which obtains the first result from the opened recordset before the while loop.

  2. $sold = array();

    Why is that an array?

    If you want to sum to $sold, threat the variable as an integer and initialize it with a 0.

    $sold = 0;
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
      $sold += $row['contract']+$row['tva'];
    
    echo "<table><tr><td>" . $sold. "</td></tr></table>";
    

It seems to me also that you may want to print the table only once. If this is true, consider to query the database with an aggregation function like SUM():

SELECT SUM(contract + iva) AS contractIva FROM users GROUP BY <some column in your table>;

The above allows to remove the while loop.

Upvotes: 2

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

you can do that via query as well so that you don't need to perform calculation on the application level, database level can do this job for you.

 select sum(col1+col2) as total from users

And you want one table instead of multiple tables I guess, if yes then do it like this:

echo "<table>
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
   $sold=$row['contract']+$row['tva'];
  echo <tr><td>" . $sold. "</td></tr>";
}
echo "</table>";

Upvotes: 0

Vali S
Vali S

Reputation: 1461

Since you already extracted a row from the result, with $row = mysql_fetch_array($result);, the script starts adding only with the next row. Th correct code would be:

 <?php
     include('connect-db.php');
    $query = "select * from users";
    $result = mysql_query($query); 
    $sold= array();

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
    $sold=$row['contract']+$row['tva'];
    echo "<table><tr>
    <td>" . $sold. "</td>
    </tr></table>";
    }
        ?>

Upvotes: 1

Related Questions