monkeyman monkeyman - 4 months ago 11
PHP Question

How to call php array twice without losing results?

I have the following code:

$qry = "SELECT * FROM Table WHERE...";
$result = $db->query($qry);
$if($db->error)die($db->error);


This returns an array of 15 students. My code then continues as such:

$faculty= $result->fetch_assoc();
if ($faculty['field'] == 1)
die();

while($students = $result->fetch_assoc()) {
/*display all students*/
}


The problem I'm having is that my while loop is only displaying 14 students, when I need it to display all 15. I believe the first student is being lost when I use:

$faculty= result->fetch_assoc();


However I thought that because my
while
loop is calling on the original
$result
array I wouldn't be affected by this.

Can anyone explain what is happening here? How can I use the same array twice without having to requery my database and without losing that first result?

Answer

That happens because each time you call fetch_assoc it returns the current row and moves the pointer to the next row. You can use data_seek to adjust the result pointer to an arbitrary row in the result:

$result->data_seek(0);

Your code will look like this:

$faculty= $result->fetch_assoc();
if ($faculty['field'] == 1)
    die();
$result->data_seek(0);
while($students = $result->fetch_assoc()) {
    /*display all students*/
}

I hope this will help you.