What are some best practices for optimizing PHP code to avoid multiple SQL queries for displaying data in a table?

To avoid multiple SQL queries for displaying data in a table, one best practice is to use a single SQL query to fetch all the necessary data and then loop through the results to populate the table. This reduces the number of database calls and improves performance.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Fetch all data with a single SQL query
$stmt = $pdo->query('SELECT * FROM my_table');
$data = $stmt->fetchAll();

// Display the data in a table
echo '<table>';
echo '<tr><th>ID</th><th>Name</th><th>Email</th></tr>';
foreach ($data as $row) {
    echo '<tr>';
    echo '<td>' . $row['id'] . '</td>';
    echo '<td>' . $row['name'] . '</td>';
    echo '<td>' . $row['email'] . '</td>';
    echo '</tr>';
}
echo '</table>';