user3526161
user3526161

Reputation:

sum of array values from phpmysql

<?php
$query=mysql_query("SELECT * FROM vph");
while($array=mysql_fetch_array($query)){

    echo $a= $array['vph_weight'];// $a is like this 1,2,3,2,5,,,,,..
}
?>

I want to add $a values. Please help to add those value. I am new in PHP.

Upvotes: 0

Views: 80

Answers (2)

ihaider
ihaider

Reputation: 1350

$query=mysql_query("SELECT * FROM vph");

     $sum = 0;
     while($array=mysql_fetch_array($query)){
         $sum += $array['vph_weight'];
     }  
     echo "VPH Weight Sum: ".$sum;   

Edit: I would recommend using shankar's solution, if you need to deal only with the vph_weight value of table. But if you doing something else (except summing vph field) with the data getting from query. You can consider this solution.

Upvotes: -1

You could simply rewrite your query as below instead of doing a separate array_sum() operation overhead !

SELECT SUM(vph_weight) AS vphsum FROM vph

###The code..

$query=mysql_query("SELECT SUM(vph_weight) AS vphsum FROM vph");
while($array=mysql_fetch_array($query)){

    echo $array['vphsum'];
}

This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !

Upvotes: 3

Related Questions