Tutorials, PHP & MySQL

Counting results in PHP

A basic tutorial to show you how to use php to count the number of results in a MySQL query For this tutorial lets say you have a members site and would like to count how many members you have then print out the result.

This is very simple to do in php and there are lots of way to do it. This is a simple way of counting the members in your database.

Here's the code to count all members in your members table:

$query= "SELECT * FROM members-table WHERE member-id";
$result = mysql_query ($query) or die ('Error : ' . mysql_error());
$count = mysql_num_rows($result);
echo "Members $count";

First were selecting everything from the members-table then using the column member-id to identify different members.

Were then adding the result to a variable $result and then counting the results using mysql_num_rows and adding that to a variable called $count.

What mysql_num_rows does is count the number of affected rows in the table.

Now we have the number of members in the members-table were going to print the results:

echo "Members $count";

This will print the number from $count, For example if you have 10 members then the printed statement would be 'Members 10'

Remember there are many way to do this some are more efficient then others. 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.