I have a MySQL table that looks something like this:
+--------------------------------------+
| id | product_id | qty |
+--------------------------------------+
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 0 | 2 |
| 4 | 2 | 18 |
+--------------------------------------+
I want to get the total number of each product in the table. So for the above table, for instance, here is the result I would like:
0 -> 3
1 -> 3
2 -> 18
I figured the easiest way to do this would be to loop through the MySQL results and add the quantity of each product to an array, at the position in the array that corresponds to the product_id. I.E:
$qtyArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$qtyArray[$row[product_id]] += $row[qty];
}
I have two questions:
- Would the above work OK?
- Is there a better way of doing this?
Thank you!
MySQL does this for you: