How can SQL queries be optimized when using PHP to retrieve data from a database?

To optimize SQL queries when using PHP to retrieve data from a database, you can use prepared statements to prevent SQL injection attacks and improve performance by reducing the need for repeated query parsing. Additionally, you can limit the columns selected to only those needed, use indexes on frequently queried columns, and avoid using SELECT * to fetch all columns unnecessarily.

// Example of using prepared statements in PHP to optimize SQL queries
$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)) {
    // Process the retrieved data
}