Dominik Kuchar
Dominik Kuchar

Reputation: 13

sum values from mysql

Using PHP, I can find the productId in the first table:

$stmt = $db->prepare("SELECT productId FROM boughtProducts WHERE userid = :username");
$stmt->execute(array(':username' => $_SESSION['username']));
$productId = $stmt->fetchAll();

I also have a columns with values in variables like the following:

$productId["0"]["productId"] & $productId["1"]["productId"]...

In the variables above I only get IDs where I must find my values in second table.

$stmt = $db->prepare("SELECT price FROM products WHERE id = :productid");
$stmt->execute(array(':productid' => $productId["0"]["productId"]));
$price = $stmt->fetch(PDO::FETCH_ASSOC);

This returns all numbers, which I want to SUM and store in a variable. How can I achieve this? I want to SUM price for all products which are bought by userid.

Upvotes: 0

Views: 45

Answers (1)

Niellles
Niellles

Reputation: 878

Something along these lines might work:

SELECT SUM(products.price) FROM boughtProducts, products WHERE boughtProducts.userid = :username and products.id = boughtProducts.productId

Read something about the JOIN keyword (I'm using an implicit join in my example)... also get yourself acquainted with the concept of foreign keys.

Good luck!

Upvotes: 1

Related Questions