Jump to content

Counting prices from mysql database


McMaster

Recommended Posts

Hey,

 

I am trying to calculate all of the prices in a database within one variable but it doesn't seem to work. The output I get is only the first price and not the total calculation. The code is as follows:

 

$sql = mysql_query("SELECT * FROM shopping_cart WHERE username = '".$_SESSION['myusername']."'");

$price = 0;

while ($row = mysql_fetch_assoc($sql)) {
  $sql1 = mysql_query("SELECT * FROM products WHERE id = '".$row['product_id']."'");
  $row1 = mysql_fetch_assoc($sql1);

  $price = $price + $row1['price'];
}
echo $price; //Output total price

 

Any help appreciated here guys. Thanks!

Link to comment
https://forums.phpfreaks.com/topic/204417-counting-prices-from-mysql-database/
Share on other sites

How about doing it the right way?

 

<?php
$query = "SELECT 
  SUM(price) AS totalPrice 
FROM
  shopping_cart AS c
INNER JOIN
  products AS p
ON
  p.id = c.product_id
WHERE
  c.username = {$_SESSION['myusername']}";

if(!$result = mysql_query($query)) {
  die("Query error: ".mysql_error());
}

$row = mysql_fetch_assoc($result);

echo $row['totalPrice'];

Just to beat a dead horse:

 

The only thing that irritates me worse than seeing "looping" queries is when people write the SQL statement directly in the mysql_query() function instead of create a string var. By writing directly in the query function you lose the ability to easliy debug database errors.

Just to beat a dead horse:

 

The only thing that irritates me worse than seeing "looping" queries is when people write the SQL statement directly in the mysql_query() function instead of create a string var. By writing directly in the query function you lose the ability to easliy debug database errors.

 

That's why ext/mysqli is so cool. You can extend it, so that all error handling is done WITHIN query funciton :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.