How can PHP be integrated with MySQL to retrieve and display data in a table format?
To integrate PHP with MySQL to retrieve and display data in a table format, you can use PHP's MySQLi extension to establish a connection to the database, execute a query to retrieve data, and then loop through the results to display them in an HTML table.
<?php
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Query to retrieve data from a table
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Display the data in an HTML table
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close the connection
mysqli_close($connection);
?>