PHP & MySQL: Count number of rows in a table (with & without conditions)

Updated: January 12, 2024 By: Guest Contributor Post a comment

Overview

In web development, understanding how to manage and retrieve data efficiently is fundamental. When working with databases, one of the common tasks is to find out how many rows are present in a particular table. This operation is not only useful for data analysis but also for controlling application logic, such as pagination or conditional statements. This tutorial will guide you through different methods for counting the number of rows in a MySQL table using PHP.

Prerequisites

  • Basic knowledge of PHP and MySQL.
  • A server environment with PHP and MySQL installed (such as XAMPP, MAMP, or a LAMP stack on Linux).
  • Access to MySQL database and ability to create tables.
  • A code editor for writing scripts.

Connecting to MySQL Database

Before we can count the rows, we first need to connect to the MySQL database. For the sake of this tutorial, we’ll use mysqli, which is a PHP extension to communicate with MySQL databases. Below is an example of how a connection might be set up:

<?php

$servername = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

echo 'Connected successfully';

?>

Counting all rows in a table

Let’s start with the simplest scenario – counting all rows of a table. Assume you have a table named users. To count the number of rows, execute an SQL statement to select a count of all the rows:

<?php

$sql = 'SELECT COUNT(*) as count FROM users';
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo 'Number of rows: ' . $row['count'];
} else {
    echo '0 results';
}

$conn->close();

?>

The SELECT COUNT(*) as count statement calculates the number of rows and aliases it as count. Then, we extract this information with PHP and output it.

Counting rows with conditions

Sometimes, you might want to count rows based on a certain condition. You can achieve this by adding a WHERE clause to the SQL statement. For instance, to find out how many users are active:

<?php

$sql = 'SELECT COUNT(*) as count FROM users WHERE status = "active"';
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo 'Number of active users: ' . $row['count'];
} else {
    echo 'No active users found';
}

$conn->close();

?>

In this scenario, only users with the status marked as ‘active’ will be counted.

Optimized row counting with FOUND_ROWS()

If you are performing a LIMIT query and want to know the total number of records (without a limit), you could use the SQL_CALC_FOUND_ROWS command along with FOUND_ROWS(). However, it’s essential to understand that using SQL_CALC_FOUND_ROWS may have a performance impact on large datasets. Here is an example:

<?php

$sql = 'SELECT SQL_CALC_FOUND_ROWS * FROM users LIMIT 10';
$result = $conn->query($sql);

// Right after the above query execution, execute this:
$sqlTotal = 'SELECT FOUND_ROWS() as total';
$resultTotal = $conn->query($sqlTotal);

if ($resultTotal->num_rows > 0) {
    $rowTotal = $resultTotal->fetch_assoc();
    echo 'Total rows: ' . $rowTotal['total'];
}

$conn->close();

?>

This method retrieves the number of rows as if the LIMIT clause were not included.

Using PDO

If your application uses PDO (PHP Data Objects) instead of mysqli, the method for counting rows is similar. Below is the equivalent PDO example for counting all rows.

<?php

// PDO connection code is not shown in this example
$sql = 'SELECT COUNT(*) as count FROM users';

$stmt = $pdo->prepare($sql);
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);

echo 'Number of rows: ' . $row['count'];

?>

The code above shows how to prepare and execute the query, then fetch the result.

Conclusion

In this tutorial, we have covered how to count rows in a MySQL table using PHP, both with and without conditions. This basic concept is a cornerstone of data manipulation and is often used in reports, dashboards, and user interfaces. Regarding performance, always assess the size of your dataset and choose the counting approach that best fits your application’s needs. Whether you are a beginner or an experienced developer, knowing how to count rows efficiently can make a significant difference to the performance and user experience of your PHP applications.