How can database queries be optimized for better performance when retrieving data in PHP?

Database queries can be optimized for better performance in PHP by using indexes on columns frequently used in WHERE clauses, avoiding SELECT * and instead selecting only the necessary columns, using prepared statements to prevent SQL injection, and limiting the amount of data fetched by using pagination.

// Example of optimizing a database query in PHP
$query = "SELECT id, name, email FROM users WHERE age > :age";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);