How can using arrays in PHP to store data from database queries lead to potential performance issues or memory consumption?
Using arrays in PHP to store data from database queries can lead to potential performance issues or memory consumption because all the data retrieved from the database is stored in memory at once. This can be problematic if the dataset is large, as it can consume a significant amount of memory and slow down the application. To solve this issue, you can fetch data from the database in chunks using a limit and offset in your query, or use techniques like pagination to limit the amount of data retrieved at once.
// Example of fetching data from the database in chunks using limit and offset
$limit = 100; // Number of records to fetch at a time
$offset = 0; // Initial offset
do {
$query = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
// Process the data here
}
$offset += $limit;
} while (mysqli_num_rows($result) > 0);