Is it more efficient to use SELECT COUNT(*) or SELECT * FROM when counting records in a MySQL table in PHP?

When counting records in a MySQL table in PHP, it is more efficient to use SELECT COUNT(*) rather than SELECT * FROM. This is because SELECT COUNT(*) simply returns the number of rows that match the query criteria, while SELECT * FROM retrieves all columns for each matching row, which can be unnecessary if you only need the count. Using SELECT COUNT(*) can reduce the amount of data transferred between the database and PHP, resulting in faster query execution.

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Query to count records in a table
$sql = "SELECT COUNT(*) as count FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output the count
    $row = $result->fetch_assoc();
    echo "Total records: " . $row['count'];
} else {
    echo "0 records found";
}

// Close connection
$conn->close();