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!

0

2 Answers 2

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 } 
Sign up to request clarification or add additional context in comments.

1 Comment

The statement handle ($ordersQuery) does not contain the result set. Do you mean to iterate $orders?
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.