0

I am currently in the process of learning PDO. I am trying to have multiply while statements, using the same variable. Now, when I used normal MySQL, I just used the mysql_data_seek(); function, in order to do this.

I have this code:

$r = $dbh->prepare("SELECT * FROM memberships ORDER by sort DESC");
$r->bindParam(':id', $userdata['membership']);
$r->execute();

<?php while($upgData = $r->fetch(PDO::FETCH_ASSOC)): ?>
 echo $upgData['id'];
<?php ?>

Then further down the code, I want to use it again:

<?php while($upgData = $r->fetch(PDO::FETCH_ASSOC)): ?>
 echo $upgData['name'];
<?php ?>

Although, the second time, nothing gets printed out. Why is that?

oliverbj
  • 5,771
  • 27
  • 83
  • 178

1 Answers1

1

Pointer for fetch has reached the end of the Object. Using MySQLi or MySQL extensions it was possible to reset this pointer to the first element but PDO doesn't seem to offer such functionality AFAIK. One way to go about is to first fetch all the values in an array.

$rows = $r->fetchAll();

Then iterate over that array two times

foreach ($rows as $r) {
    echo $r['name'];
}

foreach ($rows as $r) {
    echo $r['name'];
}

Using MySQLi or MySQL extensions it was possible to reset this pointer to the first element but PDO doesn't seem to offer such functionality AFAIK.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95