How can PHP be used to dynamically display data from a MySQL database in HTML?
To dynamically display data from a MySQL database in HTML using PHP, you can establish a database connection, query the database to retrieve the data, and then use PHP to loop through the results and display them on the webpage.
<?php
// Establish connection to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data from database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Loop through results and display data in HTML
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close database connection
$conn->close();
?>