What are some best practices for optimizing PHP code when working with MySQL queries and organizing data for display in a tabular format?

When working with MySQL queries and organizing data for display in a tabular format, it is important to optimize your PHP code to improve performance. One best practice is to minimize the number of queries by fetching all necessary data in a single query and then organizing it efficiently for display.

// Example of optimizing PHP code for MySQL queries and organizing data for tabular display

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Fetch all necessary data with a single query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Display data in a tabular format
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>";

// Close MySQL connection
mysqli_close($connection);