How can PHP developers optimize database queries for better performance?

To optimize database queries for better performance, PHP developers can utilize techniques such as indexing columns used in WHERE clauses, minimizing the number of queries by using JOINs, caching query results, and using prepared statements to prevent SQL injection attacks.

// Example of optimizing a database query using prepared statements

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

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

// Bind parameters to the prepared statement
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the prepared statement
$stmt->execute();

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

// Process the results as needed
foreach ($results as $row) {
    // Do something with the data
}