What are the best practices for optimizing PHP code that involves querying databases?

When optimizing PHP code that involves querying databases, it is important to minimize the number of queries being executed, use indexes on database columns, fetch only the necessary data, and utilize caching mechanisms to reduce database load.

// Example code snippet demonstrating optimization techniques for querying databases in PHP

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

// Use indexes on database columns for faster query execution
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->bindParam(':email', $email);
$stmt->execute();

// Fetch only the necessary data from the database
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Utilize caching mechanisms to reduce database load
if ($user) {
    // Cache the user data for future use
    $cache->set('user_' . $email, $user);
} else {
    // Retrieve user data from cache if available
    $user = $cache->get('user_' . $email);
}