PHP & MySQL | Tutorials

David Carr

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. 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.