How can PHP be utilized to retrieve and display data from a database in a structured manner?
To retrieve and display data from a database in a structured manner using PHP, you can use SQL queries to fetch the data from the database and then loop through the results to display them in a structured format on the web page.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Display data in a structured format
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
Related Questions
- How can file locking mechanisms be implemented in PHP to prevent data corruption when multiple users access the same file simultaneously?
- What are the best practices for organizing and structuring user login functionality in a PHP application?
- What are some best practices for handling form data in PHP for email submission?