0

Looked all over. Can't find an answer. PHP docs not clear (to me).

I'm doing a simple MySQL sum through mysqli->query. How can I get the result with MySQLi like mysql_result?

6
  • Are you able to get the results from a regular query with mysqli? The fact that you're using sum() shouldn't change anything.
    – octern
    Commented Sep 29, 2012 at 19:27
  • 1
    assuming something like this: $res=mysqli_query($dbh,"select sum(field) from table1"); if (FALSE === $res) die("select sum failed"); follow up with $row = mysqli_fetch_row($res); $sum = $row[0];
    – tamouse
    Commented Sep 29, 2012 at 19:29
  • Ironically, I only have experience with arrays using mysqli_fetch_assoc. How would I access the single result? Using the column that was summed? An alias? Thank-you very much for your help.
    – user1382306
    Commented Sep 29, 2012 at 19:30
  • @tamouse Using "$row = mysqli_fetch_row($res);" gives "Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given"
    – user1382306
    Commented Sep 29, 2012 at 19:38
  • @JoeCoderGuy did you test the result from mysqli_query to see if it is FALSE? It will return FALSE if there was an error in the query.
    – tamouse
    Commented Sep 29, 2012 at 19:41

2 Answers 2

10

It's best if you used an alias for your SUM:

SELECT SUM(`field`) as `sum` FROM `table_name`

And then, you'll be able to fetch the result normally by accessing the first result row's $row['sum'].

0
7

Whatever is given in the SELECT statement to mysqli_query is going to return a mysql_result type if the query was successful. So if you have a SELECT statement such as:

SELECT sum(field) FROM table1

you still need to fetch the row with the result, and the value of the sum() function will be the only entry in the row array:

$res = mysqli_query($dbh,'SELECT sum(field) FROM table1');
$row = mysqli_fetch_row($res);
$sum = $row[0];