The most efficient way to count rows in a database table is by using
SQL's
COUNT() syntax in your query. It is
made for counting. You can then use the
mysql_fetch_row
function to obtain the amount from the COUNT() query. You can target
the data you want to count within your query using the WHERE clause and
assign what the field's value must equal in order to be counted.
Using
mysql_fetch_row and
COUNT() to count rows in a MySQL database table:
<?php
// include your MySQL database connection script here
require_once "connect_to_mysql.php";
// Build sql command
$sqlCommand = "SELECT COUNT(*) FROM members";
// Execute the query here now
$query = mysql_query($sqlCommand) or die (mysql_error());
// Access the count using mysql_fetch_row
$row = mysql_fetch_row($query);
// output the value we want
echo "There are " . $row[0] . " people in my members table.";
// Free the result set
mysql_free_result($query);
// close mysql connection
mysql_close();
?>
There are 3 people in my members table.