What is the correct syntax for counting the number of database records in PHP?

When working with a database in PHP, you may need to count the number of records in a table. This can be done using a SQL query to retrieve the count of records. The result can then be fetched and used in your PHP code.

// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database_name");

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

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

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

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