How can the code snippet provided be optimized for better performance and efficiency in PHP?

The code snippet provided can be optimized for better performance and efficiency by using a single query to retrieve all the data from the database instead of making individual queries for each row. This reduces the number of database interactions and improves the overall performance of the script.

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

// Prepare a query to fetch all rows from the table
$query = $pdo->query("SELECT * FROM mytable");

// Fetch all rows at once
$rows = $query->fetchAll(PDO::FETCH_ASSOC);

// Loop through the fetched rows
foreach ($rows as $row) {
    // Process each row as needed
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}