Re: Count and sum??
| From: | Cody Caughlan | Date: | Thu, 03 Aug 2000 06:55:11 +0000 |
| Subject: | Re: Count and sum?? | ||
| References: | 1 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-1747@lists.php.net to get a copy of this message | ||
Shannon Doyle wrote:
>
> Hi Guys,
>
> Small question,
>
> Using a MYSQL query I need to return a count of the number of entries in my
> MYSQL database that meet a certain criteria, and for the life of me I cannot
> seem to get the count function to work for me. What is the best way to
> return such a value?
>
do your select statement and then use mysql_num_rows to get the size of
the result set. example:
$query = "SELECT * FROM $table WHERE <whatever your criteria is>";
$res = mysql_db_query($database, $query);
$number_of_entries = mysql_num_rows($res);
> Also I am wanting to obtain a sum of the values entered in the database that
> meet acertain criteria. (ie they are numerals and I need to add them up)
> Easy way for this too??
> Any help on these would be great as I cant seem to get count to work, and I
> am not sure on how to go about getting a sum to happen.
>
use a SELECT statement and then in a loop, read each row as an array,
grab the column you need and sum it up. like this:
$query = "SELECT integerOrFloatColumnName FROM $table WHERE <your
criteria here>";
$res = mysql_db_query($database, $query);
#check for the number of rows before you call mysql_fetch_array,
otherwise if there is no data in database for you to SELECT then this
call will fail and you will get MySQL errors
$numrows = mysql_num_rows($res);
if($nrows)
{
$sum = 0;
while($row = mysql_fetch_array($res))
{
$integerOrFloat = $row[integerOrFloatColumnName];
$sum = $sum + $integerOrFloat;
}
}
# at the end of this loop, the variable $sum now has the sum of all the
columns
#free your resources
if($res) mysql_free_result($res);
To Do: study up on mysql_fetch_array and how to access columns from a
SQL result set
Good luck,
/Cody
--
--------------------------
Cody Caughlan
codyc@cats.ucsc.edu