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
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.
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");
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;
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for