What are the best practices for optimizing PHP code that involves querying databases to improve performance and reduce unnecessary traffic?

When optimizing PHP code that involves querying databases, it's important to minimize the number of queries made and to fetch only the necessary data. One way to achieve this is by using JOIN operations to combine related tables and retrieve all required data in a single query, rather than making multiple separate queries. Additionally, utilizing indexes on frequently queried columns can improve query performance significantly.

// Example of optimizing PHP code with database queries using JOIN and indexes

// Original query without optimization
$query = "SELECT * FROM orders WHERE customer_id = $customer_id";
$result = mysqli_query($conn, $query);

// Optimized query with JOIN and indexes
$query = "SELECT o.*, c.name FROM orders o 
          JOIN customers c ON o.customer_id = c.id
          WHERE o.customer_id = $customer_id";
$result = mysqli_query($conn, $query);