This is a quick PHP function to count rows in a MySQL database table. It takes 2 parameters, which are:
$linkThis is the MySQL connection object which is made, for example, by usingmysqli_connect()ormysqli_init().$tableThe name of the table that you want to count rows for.
The function will a return an integer, the number of rows in the table.
/**
* Counts the rows in a MySQL database table
* @param object $link A link identifier returned by mysqli_connect() or mysqli_init()
* @param string $table The name of the table to count rows for.
* @return integer The number of rows in the table.
*/
function isa_count_table_rows($link, $table){
$c = 0;
$result = mysqli_query($link,"SHOW TABLE STATUS");
if ($result) {
while ($row = $result->fetch_assoc()) {
if ($table != $row['Name']) continue;
$c = $row['Rows'];
}
}
mysqli_free_result($result);
return (int) $c;
}
Usage Example
This example counts rows in a table named some_table. Be sure to insert your own database details on line 2.
// connect to database
$link = mysqli_connect($db_host, $db_username, $db_password, $db_name);
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
// count rows in a table named 'some_table'
$count = isa_count_table_rows($link, 'some_table');
printf("Table 'some_table' has %d rows.", $count);
mysqli_close($link);
Questions and Comments are Welcome