Are there any best practices for efficiently counting total records in a database with PHP?

When counting total records in a database with PHP, it is important to use efficient methods to minimize resource usage. One common approach is to use the SQL COUNT() function to directly count the records in the database without fetching all the data. This can be achieved by executing a SELECT query with COUNT() and fetching the result.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL query to count total records
$query = "SELECT COUNT(*) as total_records FROM my_table";
$statement = $pdo->prepare($query);
$statement->execute();

// Fetch the total records count
$result = $statement->fetch();
$totalRecords = $result['total_records'];

echo "Total records in the database: " . $totalRecords;