How can SQL queries be optimized for better performance in PHP?

To optimize SQL queries for better performance in PHP, you can use prepared statements to prevent SQL injection attacks and improve query execution. Additionally, you can minimize the number of queries by combining multiple operations into a single query and indexing the database tables properly.

// Example of using prepared statements to optimize SQL queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind parameters and execute the query
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use the fetched data
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}