Are there any best practices for optimizing PHP scripts that retrieve data from a database?

When optimizing PHP scripts that retrieve data from a database, it is important to minimize the number of queries, fetch only the necessary data, use indexes on columns frequently used in queries, and consider caching mechanisms to reduce database load.

// Example of optimizing PHP script to retrieve data from a database

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Retrieve data with a single query and fetch only necessary columns
$stmt = $pdo->query('SELECT id, name, email FROM users WHERE status = 1');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use indexes on columns frequently used in queries
// For example, ensure there is an index on the 'status' column in the 'users' table

// Consider caching mechanisms to reduce database load
// Implement a caching strategy using tools like Memcached or Redis