I am querying a database. Then inserting the resultant values into an array and finding their sum. This is the code:
$result=mysql_query("SELECT items FROM mytable WHERE user_id='$id'");
$array=array();
while($row=mysql_fetch_assoc($result)){
//insert values into array
$array=$row;
$sum=array_sum($row);
echo $sum;
}
This just returns the items in the array and not the sum. How do I correct that? Ps:I had tried this here earlier, but it halves the correct result:
$result=mysql_query("SELECT items FROM mytable WHERE user_id='$id'");
$row = mysql_fetch_array($result, MYSQL_NUM);
$sum = array_sum($row);
echo $sum;
Thanks
Why not just use SELECT sum(items) FROM mytable WHERE userid="$id"
? You'll save CPU if you push this kind of thing off to the database server.
$result = mysql_query("SELECT items FROM mytable WHERE user_id='$id'");
$array = array();
$sum = 0;
while($row=mysql_fetch_assoc($result)){
//insert values into array
$array[] = $row;
$sum += $row;
}
echo $sum;
This would be the code if you need both the array and the respective sum. If you just need the sum, it would be much more efficient, if you have your database do the summation by turning your query into
$result = mysql_query("SELECT SUM(items) FROM mytable WHERE user_id='$id'");
$sum = mysql_fetch_assoc( $result );
Using database layer usually is more faster than business logic
$result=mysql_query("SELECT SUM(items) AS mysum FROM mytable WHERE user_id='$id'");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
/* always use assoc to prevent yourself from errors after table's modification */
echo $row['mysum'];