How can PHP be used to fetch data from a MySQL database and display it in an HTML table?
To fetch data from a MySQL database and display it in an HTML table using PHP, you can establish a connection to the database, query the data you want, and then loop through the results to display them in a table format in HTML.
<?php
// Establish a connection to the MySQL 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 for the data you want
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display the data in an HTML table
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["email"] . "</td></tr>";
}
} else {
echo "0 results";
}
echo "</table>";
// Close the connection
$conn->close();
?>
Related questions
-
PHP stylesheets modules
-
input validation data processing output generation
-
heredoc syntax PHP SQL commands