What is the best practice for using loops to repeat table rows when displaying database records in PHP?
When displaying database records in PHP, the best practice for using loops to repeat table rows is to fetch the records from the database using a query, iterate over each record using a loop, and output the data within each row of the table. This allows for a dynamic display of records without hardcoding each row individually.
<?php
// Assume $conn is the database connection object
// Fetch records from the database
$query = "SELECT * FROM your_table";
$result = mysqli_query($conn, $query);
// Display records in a table
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>";
// Free result set
mysqli_free_result($result);
// Close connection
mysqli_close($conn);
?>
Keywords
Related Questions
- How can the output of a shell command, like 'ls -lart', be displayed in PHP when executed through shell_exec()?
- What are the best practices for managing PHP versions on a Mac system, especially for web development with Drupal?
- How can proper indentation and formatting improve code readability in PHP?