How can PHP be used to dynamically generate tables based on database data?
To dynamically generate tables based on database data in PHP, you can query the database to retrieve the necessary data, loop through the results to generate table rows, and output the HTML structure with the data inserted into the table. This allows for a flexible and automated way to display database content in a tabular format on a web page.
<?php
// Connect to the 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);
}
// Query the database to retrieve data
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Generate table structure with data
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach($row as $key => $value) {
echo "<td>".$value."</td>";
}
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close database connection
$conn->close();
?>