Jump to content


SQL data and counting them?


6 replies to this topic

#1 Marxx

    Young Padawan

  • Members
  • Pip
  • 116 posts
  • Gender:Male
  • Location:Finland

Posted 15 July 2007 - 03:27 PM

Hi all! I have this problem whit SQL data and how to count them..
Well, here's example:

ID=1 Name=Apples Stored=32
ID=2 Name=Bananas Stored=16
ID=3 Name=Oranges Stored=132

How can I count all Stored amount together? So the Stored amount should be 180
I've tryed this:

$showcount = mysql_query("SELECT Stored FROM fruits");
while($count = mysql_fetch_row($showcount)) {
$counted = $count[0] + $count[0]

echo $counted;
}

But no luck.. :/
Can someone help me whit this please.. :P


Thanks for all!

#2 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 15 July 2007 - 03:35 PM

$showcount = mysql_query("SELECT Stored FROM fruits") or die(mysql_error());
$counted = 0;
while($count = mysql_fetch_row($showcount))
  $counted += $count[0];

echo $counted;

Simple. :P

#3 bay

    Young Padawan

  • Members
  • Pip
  • 105 posts
  • Gender:Male
  • Location:Chicago, IL USA

Posted 15 July 2007 - 03:38 PM

use SUM() in your query:

$query = mysql_query( "SELECT SUM(Stored) AS totalStored FROM fruits" );
$fetch = mysql_fetch_assoc ( $query );
$totalStored = $fetch['totalStored'];

#4 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 15 July 2007 - 03:41 PM

Or you could do that, lol, I wasn't quite sure SUM() was a real function, but I finally found it on the development site. :P

#5 bay

    Young Padawan

  • Members
  • Pip
  • 105 posts
  • Gender:Male
  • Location:Chicago, IL USA

Posted 15 July 2007 - 03:43 PM

View PostDemonslay, on Jul 15 2007, 03:41 PM, said:

Or you could do that, lol, I wasn't quite sure SUM() was a real function, but I finally found it on the development site. :P

yeah, its a function. MySQL is very powerful, a lot of people add a lot of excess PHP code when they try to sort out there results when in reality they can let MySQL do everything for them.

#6 Marxx

    Young Padawan

  • Members
  • Pip
  • 116 posts
  • Gender:Male
  • Location:Finland

Posted 15 July 2007 - 03:49 PM

Wow ... Thanks guys! Both ways are nice but bays is way simple! :P

Thanks for fast reply!

#7 bay

    Young Padawan

  • Members
  • Pip
  • 105 posts
  • Gender:Male
  • Location:Chicago, IL USA

Posted 15 July 2007 - 06:13 PM

your welcome :P





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users