How can the PHP code be optimized to efficiently retrieve and display the desired data from the database?

To optimize the PHP code for retrieving and displaying data from the database, we can use prepared statements to prevent SQL injection attacks and improve performance. Additionally, we can limit the number of columns retrieved to only those needed for display to reduce unnecessary data transfer.

<?php
// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a statement to retrieve only necessary columns
$stmt = $pdo->prepare("SELECT column1, column2 FROM mytable WHERE condition = :condition");

// Bind parameters and execute the query
$stmt->bindParam(':condition', $condition);
$condition = 'value';
$stmt->execute();

// Display the retrieved data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
?>