What are some best practices for handling and displaying query results in PHP when working with MySQL databases?
When handling and displaying query results in PHP when working with MySQL databases, it is important to properly iterate through the result set and display the data in a clear and organized manner. One common approach is to use a loop to fetch each row from the result set and then display the data in a table format.
// Assuming $conn is the MySQL database connection and $query is the SQL query
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No results found.";
}