Search code examples
phpmysqlarraysperformancevar-dump

How can I create an array from a huge amount of data?


I am selecting a lot of data from my mySQL database:

 $sql = "SELECT * FROM data WHERE id = ?";  
 $q = $pdo->prepare($sql);
 $q->execute([$id]);
 $array = $q->fetchAll(PDO::FETCH_ASSOC);

 var_dump($array);

I want to store this data into an array and after work with this array in a loop. My problem is now, that I have such an immense amount of data, that the array is loading and loading and my system is overwhelmed. Is there a way to create an array with a huge amount of data with a better performance?


Solution

  • The fetchAll() function maps the whole record to the variable.

    Mapping one row per iteration will be considerably faster

    $q->execute([$id]);
    
    $i = 0;
    while ($row = $q->fetch()) {
        // do something with $row
        $i++;
    }