FaserF
FaserF

Reputation: 19

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.

Upvotes: 0

Views: 356

Answers (1)

spencer7593
spencer7593

Reputation: 108370

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

Upvotes: 1

Related Questions