How can PHP be used to output database entries in both rows and columns?
To output database entries in both rows and columns using PHP, you can fetch the data from the database and then iterate through the rows to display them in a tabular format. You can use HTML table tags to structure the output and loop through the data to populate the rows and columns accordingly.
<?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_name";
$result = $conn->query($sql);
// Output data in rows and columns
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
Related Questions
- In PHP, what are the differences between using a while loop and a foreach loop to iterate through an array, and when is each method more appropriate?
- What are the advantages of using auto_increment for unique IDs in a database table for news entries in PHP?
- How can developers ensure the code quality and usability of PHP-based CMS platforms when evaluating demos or open-source options?