What are the best practices for optimizing SQL queries in PHP to improve performance when working with large datasets?

When working with large datasets in PHP and SQL queries, it is important to optimize the queries to improve performance. Some best practices include using indexes on columns frequently used in WHERE clauses, limiting the number of columns retrieved in SELECT queries, and avoiding using SELECT * to fetch all columns. Additionally, consider using prepared statements to prevent SQL injection attacks and caching query results when possible.

// Example of optimizing SQL query in PHP using indexes and limiting columns
$query = "SELECT id, name FROM users WHERE age > 18";
$result = mysqli_query($conn, $query);

// Example of using prepared statements in PHP to prevent SQL injection
$stmt = $conn->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

// Example of caching query results in PHP
$key = 'cached_query_results';
if (!($data = apc_fetch($key))) {
    $query = "SELECT id, name FROM users";
    $result = mysqli_query($conn, $query);
    $data = mysqli_fetch_all($result, MYSQLI_ASSOC);
    apc_store($key, $data, 3600); // Cache for 1 hour
}