How can SQL queries be optimized in PHP to retrieve and display data more efficiently?

To optimize SQL queries in PHP, you can use prepared statements to prevent SQL injection attacks and improve performance by reusing query execution plans. Additionally, you can limit the number of columns retrieved to only those needed and avoid using SELECT * which can slow down queries. Finally, consider indexing columns that are frequently used in WHERE clauses to speed up data retrieval.

// Example of optimizing SQL query in PHP using prepared statements
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT column1, column2 FROM mytable WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

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