Forum Moderators: coopster

Message Too Old, No Replies

Trouble counting records in db

I can't count :(

         

riverstyx

9:28 pm on Jun 11, 2005 (gmt 0)

10+ Year Member



If you gurus have a minute, I can't find a decent example in my books. I'm creating a subscriber report and just want to echo out the total number of subscribers, how many male, how many female etc. I have tried variations on this:

$sql = "SELECT COUNT(gender) as totalrows FROM subscribers WHERE gender=Male";

$result = mysql_query($sql, $conn);

echo ("There are $result male subscribers.")

but nothing is printing. Do I need to do something with "$i" and "++"? If you are selecting a specific record and not the entire row is the result still an array?

RS

riverstyx

10:10 pm on Jun 11, 2005 (gmt 0)

10+ Year Member



I meant 'field' above -- if I'm pulling data from just one field and not the entire row is the result an array?

RS

arran

10:59 pm on Jun 11, 2005 (gmt 0)

10+ Year Member



Hi riverstyx,

This should do the trick:

$sql = "SELECT COUNT(gender) as totalrows FROM subscribers WHERE gender=Male";
$results = mysql_query($sql, $conn);
$totalrows = mysql_result($results,0,"totalrows");
echo ("There are $totalrows male subscribers.")

or you could use the 'mysql_num_rows' function:

$sql = "SELECT * as totalrows FROM subscribers WHERE gender=Male";
$results = mysql_query($sql, $conn);
$totalrows = mysql_num_rows($results);
echo ("There are $totalrows male subscribers.")

Hope this helps.

Skeleton

11:12 pm on Jun 11, 2005 (gmt 0)

10+ Year Member



This should work:

$sql = "SELECT COUNT(gender) as totalrows FROM subscribers WHERE gender=Male";

$result = mysql_query($sql, $conn);

$rec = mysql_fetch_assoc($result);

echo ("There are ".$rec["totalrows"]." male subscribers.")

riverstyx

12:09 am on Jun 12, 2005 (gmt 0)

10+ Year Member



I will give both a go and see what happens. Thanks a lot...

RS