Skip to content
PHP Logo

How can PHP developers efficiently fetch and store database query results into arrays without overwriting the data in a loop?

When fetching database query results in a loop, PHP developers can efficiently store the data into arrays without overwriting it by using different keys for each row in the array. This can be achieved by incrementing a counter variable for each iteration of the loop and using it as the key when assigning the row data to the array.

php
// Initialize an empty array to store query results
$results = array();

// Execute the database query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Loop through the query results and store them in the array
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    $results[$i] = $row;
    $i++;
}

// Now $results array contains all the query results without overwriting them