How to Count Records in a PHP MySQL Query

Written by lisa nelson
  • Share
  • Tweet
  • Share
  • Email

You can count the number of records in a MySQL table with PHP for a number of purposes, such as collecting statistics on the number of registered users on a website, calculating the number of pages to display when paginating the results of a search, or to estimate the time needed to update all the rows in a table. MySQL has a function specifically for this purpose: the "COUNT" function.

Skill level:

Other People Are Reading


  1. 1

    Create a new file with a ".php" extension, and open it using a text editor. Write code that will establish a connection to your MySQL database using PHP's "mysql_connect" and "mysql_select_db" functions.The first function takes three parameters: the server on which the database is located and the username and password with which to connect. The second function takes a single parameter: the database you wish to use. Here is an example:


    $handle = mysql_connect('localhost', 'root', 'my_password');


    Replace "my_password" and "my_database" with your password and database.

  2. 2

    Write a segment of code that will execute a select query against the table whose entries you wish to count using PHP's "mysql_query" function and assign the result to a new variable. Use "COUNT(*) AS count" as the select expression to retrieve the number of rows as "count." Here is an example:

    $result = mysql_query("SELECT COUNT(*) AS count FROM recipes");

  3. 3

    Write a segment of code to execute the "mysql_fetch_assoc" function. The function will fetch the first, and only, row as an associative array, and assign the result to a new variable. Access the index "count" in the new variable to get the number of rows. Here is an example:

    $row = mysql_fetch_assoc($result);

    $count = $row['count'];

    echo "Rows: " . $count;

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.