How can SQL statements be optimized to avoid unnecessary database queries in PHP?

To avoid unnecessary database queries in PHP, SQL statements can be optimized by using techniques such as caching query results, minimizing the number of queries, and using indexes on frequently accessed columns. Additionally, using parameterized queries can help prevent SQL injection attacks and improve performance.

// Example of optimizing SQL statements by caching query results
$result = $cache->get('cached_query_result');

if (!$result) {
    $query = "SELECT * FROM table WHERE condition";
    $result = $db->query($query);
    
    $cache->set('cached_query_result', $result);
}

// Process the query result
foreach ($result as $row) {
    // Do something with the data
}