What is the best practice for retrieving the number of records in a table using PHP and MySQL?

To retrieve the number of records in a table using PHP and MySQL, you can use a SQL query to count the rows in the table. This can be achieved by executing a SELECT COUNT(*) query on the table you want to retrieve the count for. Once the query is executed, you can fetch the result and use it in your PHP code.

<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Query to retrieve the number of records in a table
$sql = "SELECT COUNT(*) AS total_records FROM table_name";
$result = mysqli_query($connection, $sql);

// Fetch the result
if ($result) {
    $row = mysqli_fetch_assoc($result);
    $total_records = $row['total_records'];
    echo "Total records in table: " . $total_records;
} else {
    echo "Error: " . mysqli_error($connection);
}

// Close connection
mysqli_close($connection);
?>