Skip to content
PHP Logo

What are the potential pitfalls of trying to store each query result in a separate variable?

Storing each query result in a separate variable can lead to code redundancy and make it difficult to manage and scale the codebase. Instead, it is better to store the results in an array or object to easily iterate over them and access the data as needed.

php
// Store query results in an array
$queryResults = [];

// Execute queries and store results in the array
$queryResults['result1'] = mysqli_query($connection, "SELECT * FROM table1");
$queryResults['result2'] = mysqli_query($connection, "SELECT * FROM table2");

// Access the query results from the array
foreach ($queryResults as $key => $result) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Process each row as needed
    }
}