Reset MySqli pointer?

2019-07-16 05:35发布

I'm struggling a bit with resetting a pointer. I want to do this because I'm going to use the same query twice in the same script. As far as I can work out I can do this with resetting the pointer after I've looped trough the fetched array. If there is a better way to do this, I'd love to hear it.

Anyway, this is what I got.

$getEvent = $connection->prepare("SELECT * BLABLA FROM BLABLA");

$getEvent->bind_param("i", $eventID); 

    $getEvent->execute();
    $getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);

while($getEvent->fetch())
    {
        // Do stuff
    }

// Then bunch of code, before finally another

//$getEvent->execute(); //Script doesn't work without this and next line
//$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);

 while($getEvent->fetch())
    {
      // Do other stuff
    }

I've tried with $getEvent->data_seek(0); but no luck. The script only works if I redeclare $getEvent->bind_result. Thanks in advance for any replies.

1条回答
2楼-- · 2019-07-16 05:59

This places unnecessary extra strain on the database server. Rather than rewind and reuse the result set, store the whole thing in an array to begin with. You may then use it as many times and different ways as you like in the PHP application code.

Update Fixed code so it should work with MySQLi rather than PDO. Also, made the results into an associative array.

$results = array();
while($getEvent->fetch())
{
    $results[] = array('eventMember'=>$eventMember, 'eventStaff'=>$eventStaff, 'eventMemberID'=>$eventMemberID, 'eventMemberSuper'=>$eventMemberSuper);
}

// Now use $results however you need to.
查看更多
登录 后发表回答