How can data be queried from a MySQL database using PHP and displayed in a web page?
To query data from a MySQL database using PHP and display it on a web page, you can use the MySQLi or PDO extension in PHP. First, establish a connection to the database, then write a SQL query to retrieve the data. Next, execute the query and fetch the results. Finally, loop through the results and display them on the web page.
<?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);
}
// Write SQL query to retrieve data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display data on web page
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>