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
?
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']
.
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];
$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];