What are some best practices for dynamically populating a table in PHP with data from a MySQL database?
When dynamically populating a table in PHP with data from a MySQL database, it is best practice to use a loop to fetch the data from the database and generate the table rows accordingly. This ensures that the table is populated with the correct data and can easily adapt to changes in the database.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch data from database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Generate table rows dynamically
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 database connection
mysqli_close($connection);
?>