How can PHP be used to retrieve and display query results from a MySQL database in a table format on a webpage?
To retrieve and display query results from a MySQL database in a table format on a webpage using PHP, you can first establish a connection to the database using mysqli_connect(), then execute a SELECT query to fetch the data. Next, you can loop through the results and output them within HTML table tags to display the data in a tabular format on the webpage.
<?php
// Establish connection to MySQL database
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute SELECT query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Display results in a 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 connection
mysqli_close($connection);
?>