Monday, August 23, 2010

Best way to get all rows in a mysql table - mysql_num_rows() or count()

Normally there are two ways to get the total number of rows in a mysql table.

$result = mysql_query("select count(id) from table");
$data = mysql_fetch_array($result);
$all_rows = $data[0];


$result = mysql_query("select id from table");
$all_rows = mysql_num_rows($result);

As you have guessed the best server resource friendly method is to use mysql count() function instead of returning all the rows as a result-set to use in php mysql_num_rows() function.

1 comment: