W3docs

Checking for an empty result (PHP, PDO, and MySQL)

In PHP, you can use the PDO (PHP Data Objects) extension to interact with a MySQL database.

In PHP, you can use the PDO (PHP Data Objects) extension to interact with a MySQL database. To check if a SELECT query returned an empty result set, do not rely on rowCount(). In PDO/MySQL, rowCount() is not guaranteed to return the correct number of rows for SELECT statements and often returns -1 or 0. Instead, use the fetchAll() method, which returns an array of rows. If the query returns no results, the array will be empty.

Example:

Example of using the fetchAll() method on the PDO statement in PHP

<?php
// Assume $pdo is a valid PDO instance
$stmt = $pdo->query('SELECT * FROM users WHERE id = 1');
$result = $stmt->fetchAll();
if (empty($result)) {
    echo "No results found.";
} else {
    // process the results
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

For better performance when you only need to verify if at least one row exists, you can use fetch() instead. It retrieves only the first row and stops, making it more memory-efficient than fetchAll().