What are potential pitfalls when using COUNT() in SQL queries in PHP?
When using COUNT() in SQL queries in PHP, one potential pitfall is that the query may return a result set with a single row containing the count value. To access this count value, you need to fetch the result and retrieve the count value from the fetched row. This can be done using fetchColumn() method in PDO or fetch_assoc() method in mysqli.
// Using PDO
$query = "SELECT COUNT(*) FROM users";
$stmt = $pdo->query($query);
$count = $stmt->fetchColumn();
echo "Total number of users: " . $count;
// Using mysqli
$query = "SELECT COUNT(*) FROM users";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$count = $row['COUNT(*)'];
echo "Total number of users: " . $count;