简体   繁体   中英

Get the sum of all rows in one table

I've tried to get the sum of all rows from one table with the following code, but sadly my database gives me "NULL" back.

PHP:

$get_cash=mysqli_query($db, "SELECT SUM(price) FROM products WHERE ID='$F_User_ID'"); 
$fetch_cash = mysqli_fetch_assoc($get_cash); 
$cash = $fetch_cash["cash"]; 
echo "<p>Money spent already: $cash €</p>";

MySQL:

MariaDB [database]> SELECT SUM(price) FROM products WHERE ID='100001';
+------------+
| SUM(price) |
+------------+
|       NULL |
+------------+
1 row in set (0.00 sec)

So I want to get the sum of how much money the Person F_User_ID has already spent in all products he has bought.

We can replace a NULL with a zero, and we can assign an alias to the expression to be used as the column name in the resultset. If this query executes, it will return a single row containing a column named cash .

SELECT IFNULL(SUM(price),0) AS `cash` FROM products WHERE id = 'someval'

Recommended reading:

Exploits of a Mom: https://xkcd.com/327/ aka Little Bobby Tables

OWASP SQL Injection: https://www.owasp.org/index.php/SQL_Injection

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