ThePostyMan ThePostyMan - 8 days ago 5
PHP Question

PHP: I can't get reset() to work on my nested MySQLi dataset

It seems like this should be pretty straight forward, so I feel like I am missing something simple. I run two separate queries and they get assigned to an associative array variable.The queries run fine and the data is there. I am trying to iterate through one dataset inside the other dataset using while loops. It runs fine the first time through but I can't get the nested dataset to reset so I can iterate through it again. In the code and results seen below you can see that the data is indeed there because it gets skipped over by the conditional IF statement. Additionally, if I change the nested query from ascending to descending I get the second set of data and not the first (I only have two data points in the first query while I am creating and testing).

It seems like the reset() function should do what I am looking for, but it doesn't accomplish anything. I hope I am just missing something really simple.

I even tried setting the $rowDate array to a blank array and NULL both before and after the While loop to force it to refetch the data, but that did nothing as well.

Code snippet:

$studSet = mysqli_query($connection, $queryStud);
confirmQuery($studSet);

$dateSet = mysqli_query($connection, $queryDate);
confirmQuery($dateSet);

while ($rowStud = mysqli_fetch_assoc($studSet)) {
$studID = $rowStud['ID'];
$sFName = $rowStud['FName'];
$sLName = $rowStud['LName'];
$output .= "<p>" . $sFName . " " . $sLName;
while ($rowDate = mysqli_fetch_assoc($dateSet)) {
$output .= "<br />" . current($rowDate) . "&nbsp;&nbsp;&nbsp;"; //here strictly for debugging
if ($studID == $rowDate['studentID']) {
$output .= $rowDate['timeStamp'];
}
}
reset($rowDate);
$output .= "</p>";
$output .= "current " . current($rowDate) . " element"; //here strictly for debugging
}

return $output;


Result:

CodeResult

Thanks in advance for your help.

Answer

Yes you are missing two key points here:

1) You are trying to use reset() on the record, which doesn't make sense, I would understand better if you tried to reset() $dateSet, which is the query result.

2) $dateSet is not a regular array, but a MySQLi resource, that means you can't use regular PHP array functions on it. The same you use mysqli_fetch_assoc() to extract one row, you use mysqli_data_seek() to obtain the same effect than reset(), so your code would be:

mysqli_data_seek($dateSet, 0);

(which replaces the reset() call)