How can PHP be used to retrieve information from a database and display it on a webpage?
To retrieve information from a database and display it on a webpage using PHP, you can use the mysqli extension to connect to the database, execute a query to retrieve the desired data, and then loop through the results to display them on the webpage.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute query
$sql = "SELECT * FROM table";
$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();
?>
Related Questions
- How can PHP developers efficiently store and retrieve language-specific text data from a database to improve performance?
- Are there any best practices for upgrading PHP versions to avoid breaking changes in libraries like Zend Search?
- What potential security risks are associated with using register-globals in PHP?