Web Hosting Talk







View Full Version : PHP Adding


Danny159
08-06-2008, 02:00 PM
Hey,

I have been doing this for ages! and its annoying me... Can someone please help...

here is my code

<?php
$result = mysql_query("SELECT * FROM projects");
while($rows = mysql_fetch_array($result)){
$price = $rows["price"];
$exp = "$price:";
$for = explode(':', $exp, -1);
foreach($for as $key);
$add_up = ceil($key + $key);
echo "$key";
}
?>

All I want it to do is add up all the $price's so say in to database it had

0.55
558.00
2.00

it would echo "560.55"
but I cant get it to add them...
the above code echos "0.00250.00555.441587.0035.50"

Help would be grate...

Danny

Edevere
08-06-2008, 02:07 PM
what's wrong with "select SUM(price) from projects"?

Danny159
08-06-2008, 02:11 PM
What would that be?

<?php
$result = mysql_query("SELECT SUM(price) FROM projects");
echo "$result";
?>

????

vibrokatana
08-06-2008, 02:16 PM
It is probably looping through the rows and since there is no breaking character it looks like they were thrown together. Add in a '<br>' and you should see proper numbers.

Also do I see a serialized column? That is probably a bad idea, and can be avoided with a relational design.

Danny159
08-06-2008, 02:21 PM
In phpmyadmin, SELECT SUM(`price`) FROM projects echos it right but in the script it echos Resource id #7

vibrokatana
08-06-2008, 02:25 PM
In phpmyadmin, SELECT SUM(`price`) FROM projects echos it right but in the script it echos

Use the AS keyword to assign a column name:

"SELECT SUM(price) AS SumPrices FROM projects"

Then you can access it as before using "SumPrices" (Or whatever else you want to call it).

ex:

$result = mysql_query("SELECT SUM(price) AS SumPrices FROM projects");
$row = mysql_fetch_array($result);
echo $row['SumPrices'];

Danny159
08-06-2008, 02:29 PM
Ah, Thanks alot! A+++ service. You have helped me learn something today thanks guys