How can PHP be used to display data from a database in a structured format?
To display data from a database in a structured format using PHP, you can first establish a connection to the database, query the data you want to display, and then loop through the results to output them in a structured format, such as a table or list.
<?php
// Establish a connection to the database
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Query the database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Display data in a structured format
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['column1'] . "</td>";
echo "<td>" . $row['column2'] . "</td>";
// Add more columns as needed
echo "</tr>";
}
echo "</table>";
// Close connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What are some common issues with encoding special characters in PHP when sending HTML emails?
- What potential pitfalls can occur when using if-statements to limit font sizes in PHP and how can they be avoided?
- In what scenarios would it be more efficient to store text patterns in a database or text file before extracting specific information using PHP?