How can I count the number of records in a MySQL table using PHP?

To count the number of records in a MySQL table using PHP, you can execute a SQL query to select the count of rows from the table. This can be done by connecting to the MySQL database, executing the query, fetching the result, and then displaying the count.

<?php
// 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);
}

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

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

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