What are some best practices for optimizing SQL queries in PHP applications?

One best practice for optimizing SQL queries in PHP applications is to use parameterized queries instead of directly concatenating user input into the query string. This helps prevent SQL injection attacks and can improve query performance. Another best practice is to properly index your database tables to speed up query execution. Example PHP code snippet for using parameterized queries:

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

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

// Bind the parameter value
$stmt->bindParam(':username', $username);

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

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