How can database results be effectively displayed in an HTML table using PHP?
When displaying database results in an HTML table using PHP, you can retrieve the data from the database, loop through the results, and then output each row as a table row (<tr>) with each column as a table data cell (<td>). This can be done by using PHP's database functions to query the database and fetch the results, and then using HTML code to structure the data into a table format.
<?php
// Connect to 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);
}
// Query database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display results in HTML table
echo "<table>";
echo "<tr><th>Column 1</th><th>Column 2</th></tr>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['column1'] . "</td><td>" . $row['column2'] . "</td></tr>";
}
} else {
echo "<tr><td colspan='2'>No results found</td></tr>";
}
echo "</table>";
// Close connection
$conn->close();
?>
Keywords
Related Questions
- Are there any common pitfalls to avoid when deciding between using multiple SQL queries with joins or a single SQL query with PHP calculations for a statistical output in PHP?
- How can PHP developers effectively debug issues related to $_GET parameters not being set or passed correctly?
- How can PHP beginners efficiently handle date manipulation tasks like converting a day number into a specific date format?