What are the best practices for handling database query results and resource variables in PHP to avoid unintended behavior like premature loop termination?

When handling database query results and resource variables in PHP, it is important to properly free up resources and avoid unintended behavior like premature loop termination. One common practice is to fetch all results from the query into an array before processing them, rather than directly iterating over the query result resource. This ensures that the database connection is not tied up during processing and prevents issues like premature loop termination.

// Fetch all results into an array before processing
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if ($result) {
    $data = mysqli_fetch_all($result, MYSQLI_ASSOC);
    
    // Free up the result variable
    mysqli_free_result($result);
    
    // Process the data array
    foreach ($data as $row) {
        // Handle each row here
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}