MyBB Hacks

Full Version: The Sum Of All Rows: Use PHP or MySQL to Do The Math?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Which is better / faster / less server load* for adding up the value of all rows in one field:
*Generally speaking: not knowing how many rows. Tongue

Use Mysql, into a single $result variable:

Code:
SELECT sum( data_field ) FROM `somewhere`


or
Something similar to this*
*html table optional, just asking about the PHP part

PHP Code:
<table border=1>
<?php
// source = http://www.wellho.net/forum/Writing-PHP/math-in-php-mysql.html

$DBhost = "localhost";
$DBuser = "mymy";
$DBpass = "knotpass";
$DBName = "yummydata";
$table = "fred";
$sum = 0;
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database");
mysql_select_db("$DBName") or die("Unable to select database $DBName");
$result = mysql_query("SELECT * FROM $table");
while ($row = mysql_fetch_row($result)) {
   print ("<tr><td>$row[0]</td><td>$row[1]</td></tr>");
   $sum += $row[1];
   }
?>

</table>

<?php
print "Total is $sum";
?>


  • Note: I almost decided MySQL would obviously be faster, and deleted the post, but... Is PHP possibly much better for calculations, while MySQL is optimized for i/o?
ty ZB/Y ...and / or anyone else.
As you guessed, MySQL will always be faster.
PHP, being a fully fledged scripting language is more versatile.
Well it works  Smile

PHP Code:
<?php

// db connect
$sql = "SELECT sum( points ) FROM `mybb_users` ";
$result=mysql_query($sql) or die('Error query failed');

$row = mysql_fetch_array( $result );
echo $row[0];
mysql_close($link);

?>


A simple:  echo $result; doesn't work...
I wasn't expecting to use 'mysql_fetch_array' to finish off this time, but it does work. Is there a  better way to turn the "sum()" type of ( $result ) into a usable variable?

mysql_query returns a resource, if you look at the documentation for it.
You need to fetch data from this resource using mysql_fetch_array or similar, as you have done.
Reference URL's