How can you retrieve the row count for multiple tables in MySQL using PHP?
To retrieve the row count for multiple tables in MySQL using PHP, you can execute a SELECT COUNT(*) query for each table and store the result in an array. This can be achieved by connecting to the MySQL database using PHP, executing the query for each table, and fetching the row count result.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Array to store row counts
$rowCounts = array();
// Tables to retrieve row count
$tables = array("table1", "table2", "table3");
// Retrieve row count for each table
foreach ($tables as $table) {
$sql = "SELECT COUNT(*) as count FROM " . $table;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$rowCounts[$table] = $row['count'];
}
// Display row counts
foreach ($rowCounts as $table => $count) {
echo "Table: " . $table . " - Row Count: " . $count . "<br>";
}
// Close connection
$conn->close();
?>
Keywords
Related Questions
- What are some common debugging techniques for resolving issues with PHP scripts that generate calendar displays?
- What are the differences in functionality between using procedural PHP code and OOP PHP code for accessing and displaying data from a database?
- How does the DateTime class in PHP handle date conversions from DD.MM.YYYY format to YYYY-MM-DD format?