Reputation:
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
?
Upvotes: 0
Views: 27215
Reputation: 2218
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];
Upvotes: 7
Reputation: 174957
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']
.
Upvotes: 10