How can you retrieve data from a database and display it in a PHP script?
To retrieve data from a database and display it in a PHP script, you can use MySQLi or PDO to connect to the database, execute a query to fetch the data, and then loop through the results to display them on the webpage.
<?php
// Connect to 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);
}
// Fetch data from database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>