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

To optimize SQL queries for better performance in PHP applications, you can use prepared statements to avoid SQL injection attacks and improve query execution speed. Prepared statements allow you to separate SQL query logic from data, which can be reused with different parameters, reducing the overhead of query parsing and compilation.

// Example of using prepared statements to optimize SQL queries in PHP

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

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

// Bind parameter values to placeholders
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

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