Dominik Kuchar Dominik Kuchar - 1 year ago 97
MySQL Question

sum values from mysql

I have a PHP code, where I can find productId in first table

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

And I have a columns with values in variables like this

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

In this variables above I get only 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);

And after I'll get all numbers, I want to SUM it and store in variable, how can I do that?
I want to SUM price for all products which are bought by userid.
Maybe while, foreach?

Thanks a lot.

Answer Source

Something along these lines might work:

SELECT SUM(products.price) FROM boughtProducts, products WHERE boughtProducts.userid = :username and = 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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download