How can PHP developers optimize their code to improve performance and efficiency, especially when dealing with database queries?

To optimize PHP code for better performance and efficiency, especially when dealing with database queries, developers can use techniques like minimizing the number of queries, using prepared statements, indexing database columns, caching query results, and optimizing loops and conditional statements.

// Example of optimizing database query using prepared statements
$connection = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the query
$stmt = $connection->prepare("SELECT * FROM users WHERE id = :id");

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

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

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