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.

1 Answers1

-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.

JoeGalind
  • 3,545
  • 2
  • 29
  • 33
  • 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. –  Jul 20 '19 at 11:56
  • I edited the answer to fetch only the first 3 items. You have to invoke the fetch() function for each row – JoeGalind Jul 22 '19 at 15:20