How can PHP be used to retrieve data from a database and display it on a webpage?
To retrieve data from a database and display it on a webpage using PHP, you can establish a connection to the database, query the database to retrieve the desired data, and then loop through the results to display them on the webpage using HTML.
<?php
// Establish a connection to the 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 the database to retrieve data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display the data on the webpage
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>