Counting results in PHP

David Carr

1 min read - 7th May, 2011

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. 

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.