Forum Moderators: coopster

Message Too Old, No Replies

using sum

usin sum command with php

         

BenySay

1:14 am on Jan 22, 2004 (gmt 0)

10+ Year Member



Hi,

I'm trying to calculate to sum of a row named "prix" from a table named "vin_annee"
echo result on my page is : Array

Here is my code, what's wrong?

$sql= "SELECT sum(prix) FROM vin_annee";
$result= mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row;

NB : The type of the row is setted to "DECIMAL" and lenght "8,2" ( it's a row for price )

Thanks for your help!

jatar_k

2:27 am on Jan 22, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



try this

$sql= "SELECT sum(prix) as totale FROM vin_annee";
$result= mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['totale '];

$row is an array so you have to access it by element

BitBanger

2:38 am on Jan 22, 2004 (gmt 0)

10+ Year Member



$sql= "SELECT sum(prix) FROM vin_annee";
$result= mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row;

$row is an array. Try replacing 'echo $row;' with :


foreach ($row as $key => $value) {
echo $key . ' => ' . $value;
}

What I think you will get output is
Sum(prix) => <sum of field prix>

I hope this helps.

BenySay

2:45 am on Jan 22, 2004 (gmt 0)

10+ Year Member



Wow!

It's work fine!
Another one for you ...

If I have two row :
First one : quantity
Second one : price

And I want to multiply the quantity by the price before make the sum of the row "price"

e.g.:
2 X 4 = 8
3 X 5 = 15
I want to display to sum : 23 ( like a purchase order or a cart used for e-business)

jatar_k

2:52 am on Jan 22, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$sql= "SELECT quantity,price FROM vin_annee";
$result= mysql_query($sql);
$totale = 0;
while($row = mysql_fetch_array($result)) {
$totale += $row['quantity']*$row['price'];
}
echo $totale;

BenySay

3:08 am on Jan 22, 2004 (gmt 0)

10+ Year Member



Jatar K! You're my king!

Thank you very very munch for your help!

This is realy helpful in my projet ... If you want to take a look to the result, go to
It's a french site where you can manage your cellar online.

Thanks again

[edited by: jatar_k at 5:01 am (utc) on Jan. 22, 2004]
[edit reason] sorry no urls [/edit]