Counting MySQL Rows in PHP

The removed mysql_num_rows() function returned the number of rows in a legacy result resource. In current code, choose the counting method based on what you actually need.

Historical mysql_num_rows()

<?php
// Historical only: removed from PHP 7+
$query = mysql_query('SELECT * FROM student');
$number = mysql_num_rows($query);
?>

Best choice when you only need the total: COUNT(*)

SELECT COUNT(*) AS total
FROM student;
<?php
$total = $dbo->query(
    'SELECT COUNT(*) FROM student'
)->fetchColumn();

echo 'Total records = ' . $total;
?>

Counting filtered rows safely

<?php
$stmt = $dbo->prepare(
    'SELECT COUNT(*) FROM student WHERE class = :class'
);
$stmt->execute(['class' => 'Four']);
$total = (int) $stmt->fetchColumn();
?>

MySQLi result row count

<?php
$result = $connection->query(
    'SELECT id, name FROM student'
);
echo $result->num_rows;
?>
PDO note: do not use PDOStatement::rowCount() as the general way to count rows returned by a SELECT query. Use SQL COUNT(*) when the count itself is the result you need.

Related: SQL COUNT(), SELECT, WHERE filtering, affected rows after data changes, and result column count.

For application-level examples, see PDO row-count notes, MySQLi num_rows, and PHP pagination. Row counts are also commonly needed after INSERT, UPDATE, and DELETE, but those data-change operations use affected-row semantics rather than SELECT result-row counting.

← All PHP & MySQL topics




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer