What is the recommended approach for displaying data from a MySQL database in a table with two columns using PHP?
To display data from a MySQL database in a table with two columns using PHP, you can fetch the data from the database and then loop through the results to create rows in the table with two columns. You can use HTML table tags within your PHP code to structure the data in a visually appealing way.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch data from database
$query = "SELECT column1, column2 FROM table";
$result = mysqli_query($connection, $query);
// Display data in a table with two columns
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['column1'] . "</td>";
echo "<td>" . $row['column2'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close connection
mysqli_close($connection);
?>
Related Questions
- What best practices should be followed when naming methods in PHP classes to avoid conflicts or confusion?
- How can the use of auto increment for Primary Keys in a database table prevent integrity constraint violations in PHP?
- How can one efficiently handle arrays with duplicate entries in PHP to ensure optimal code execution?