0

I want to iterate through an object 3 times, but the array methor 'reset' doen't work on object.

// DB connection works, fetch mode is FETCH_OBJ an cannot be changed for this question, code is simplified $a = $pdo->query("SELECT name FROM items"); for ($i = 0; $i < 3; $i++){ foreach ($a as $b) echo $b->name; } 

I only can iterate once.

4
  • Why do you run the outer loop? Commented Jul 20, 2019 at 11:54
  • to have 3 times a complete foreach loop Commented Jul 20, 2019 at 11:58
  • Just fetch all into an array. Thats the simple solution. But seems like you can set the cursor position - see f.e. stackoverflow.com/a/14103276/3411766 Commented Jul 20, 2019 at 14:05
  • What is the output of $a Commented Jul 20, 2019 at 22:22

1 Answer 1

-1

This is how you should do this:

$sql = 'SELECT name FROM items'; try { $stmt = $pdo->query($sql); for ($i=0; $i<3; $i++) { $row = $stmt->fetch(); echo($row['name']); } $stmt = null; } catch (PDOException $e) { print $e->getMessage(); } 

The ->fetch() command gets you the next line of your dataset.

Sign up to request clarification or add additional context in comments.

2 Comments

Please look at my code. I want to repeat the foreach loop 3 times ( using for loop). I only get output for 1 complete iteration of the foreach loop.
I edited the answer to fetch only the first 3 items. You have to invoke the fetch() function for each row