
At some point in time, you’ll need to know either how many rows were returned in your result resource or how many rows match your query. While these two may seem the same, they use different methods to get the result and how different use cases. As such, we’ll take a look at these separately.
Number of Rows Returned
In your code, you may want to check how many rows where returned to you from your query. Commonly, you’ll check to see if you have more than 0 (or not 0) rows to work with (otherwise you may encounter errors while trying to process non-existing rows). We will accomplish this by using the mysql_num_rows() function, which takes a resource as a parameter. You cannot give this function the result of mysql_fetch_assoc() (or similar), the original resource is required. The function will return the number of rows. Let’s have a look at an example of this function:
[php]$query = mysql_query("SELECT * FROM posts");
if (mysql_num_rows($query) > 0) {
// Do something with the data
}[/php]
Number of Matching Rows
This method allows you to retrieve the number of rows that match your query, without actually retrieving the data. This is preferable if you will not need this data, as you will not need to waste processing power to download the data. With this method, MySQL will do all the heavy lifting and give you the result as a single “row”. This method utilizes a select query, where you wrap the field in COUNT(). For example:
[sql]SELECT COUNT(*) FROM posts WHERE type=’page’[/sql]
On the PHP side, you will still get the standard resource returned to you. If you use mysql_fetch_assoc() on it, the array key of the number will be what you used in the query (in this case, the key would be COUNT(*)). Because that will look messy in your code ($array['COUNT(*)'] is a pain to type out), you may choose to use mysql_fetch_row(), which will return a numerical array to you (so you would use $array[0] instead to get the number of rows). Let’s have a look at an example:
[php]$query = mysql_query("SELECT COUNT(*) FROM posts WHERE type=’page’");
$array = mysql_fetch_row($query);
echo ‘Number of pages: ‘ . $array[0];[/php]
The Main Difference
The main difference between these two methods is the fact that with the former, you have all the data that you’re counting available to you. With the latter method, you don’t have the data available. If you just need the number of rows (without needing the data) use the second method, which will be much quicker and less resource-intensive.