简体   繁体   中英

Set SQL SUM() query to a PHP variable, and echo result

I am trying to pull in the sum of all values in a database column, assign it to a PHP variable and display the value.

$total_drop_query = mysqli_query("SELECT SUM(total_drops) FROM pi_data");

$row = mysqli_fetch_assoc($total_drop_query);

$total_drops = $row['total_drops'];

echo $total_drops;

This code isn't displaying any results, and it's driving me crazy!

Thanks in advance.

You are not printing SUM but 'total_drops' value , that in sql you have not select. It's good thing to use an alias when you use SUM or Count in sql:

SELECT SUM(total_drops) AS something FROM pi_data"

so:

$total_drops = $row['something'];

I've set up a table with your structure - the query works well so I think that you have the error in accessing the data.

I suggest you using aliases

SELECT SUM(total_drops) AS a FROM pi_data

access is possible via

$total_drops = $row['a'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM