3

I am fetching the results from a db with PDO::FETCH_ASSOC. The issue is that I am doing it twice in the same file. Is that a known issue? What would be the alternative?

Here is my code:

FIRST TIME

while($row = $ordersQuery->fetch(PDO::FETCH_ASSOC)) 
        {
            $totalAmount += $row['clientPrice']/100; 
        }
        echo $totalAmount;

SECOND TIME

    while($row = $ordersQuery->fetch(PDO::FETCH_ASSOC)) 
            {
    ....
    }

Whenever I remove the first fetching, the second works fine. If I have both, the second does not return anything.

Thanks!

samyb8
  • 2,560
  • 10
  • 40
  • 68

2 Answers2

7

You can't fetch from the DB multiple times like this. Do this instead:

$orders = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);

...

foreach ($orders as $val) {
    // stuff 1
}

...

foreach ($orders as $val) {
    // stuff 2
}
JRL
  • 840
  • 6
  • 18
0

Use fetchAll() which will return an array. You then can loop through it as many times as you want:

$orders = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);