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
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'];

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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 :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.