What is the best practice for retrieving the total number of rows in a MySQL table using PHP?
To retrieve the total number of rows in a MySQL table using PHP, you can execute a SQL query to count the rows in the table. This can be achieved by using the COUNT() function in a SELECT query. After executing the query, you can fetch the result and store it in a variable for further use.
<?php
// Connect to MySQL database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to count the total number of rows in a table
$sql = "SELECT COUNT(*) as total_rows FROM table_name";
// Execute the query
$result = $conn->query($sql);
// Fetch the result and store it in a variable
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$totalRows = $row['total_rows'];
echo "Total number of rows: " . $totalRows;
} else {
echo "No rows found";
}
// Close the connection
$conn->close();
?>