How can PHP be used to output SQL data in a table format?
To output SQL data in a table format using PHP, you can fetch the data from the database using SQL queries and then loop through the results to generate HTML table rows. You can use functions like mysqli_fetch_assoc() to retrieve each row as an associative array and then output the data within table cells.
<?php
// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch data from the database
$sql = "SELECT * FROM your_table";
$result = mysqli_query($conn, $sql);
// Output data in a table format
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
// Close connection
mysqli_close($conn);
?>
Keywords
Related Questions
- In the provided PHP code, why does the script display one less article than the specified limit?
- Why does the dbsettings file initiate a database connection and what impact does it have on the code?
- How can the principles of single responsibility and separation of concerns be applied to PHP classes, especially when dealing with user management?