How to Find the Number of Rows in a MySQL Table Using PHP


In this article, using PHP, we will show you how you can find the number of rows which a MySQL table is comprised of.

This can be useful for not just finding the total number of rows in the entire table but can also be used to find the number of rows where a certain condition is specified, for example, finding the number of total rows where a person's last name is 'Smith' for a database of names, for instance.

This is also especially useful when we're looking up the availability of a user name when a new registrant is signing up to join something. We can check if there are any rows in the table where that user name exists. If it does exist, then we know it is unavailable. If it doesn't, then we know that the user name can be used.

To find the number of total rows of a MySQL table, we first connect to the database and then we include the following code:

The first line of code selects all the rows of all the columns from the table table_name and stores it in the variable $result. Then we use the PHP function mysql_num_rows() to find out how many rows are in the table. We store this result in the $count variable, which we then display with the echo function.

Below is a MySQL table representing different fruits: