我有以下代码:
$qry = "SELECT * FROM Table WHERE...";
$result = $db->query($qry);
$if($db->error)die($db->error);
这将返回一个包含 15 名学生的数组。然后我的代码继续这样:
$faculty= $result->fetch_assoc();
if ($faculty['field'] == 1)
die();
while($students = $result->fetch_assoc()) {
/*display all students*/
}
我遇到的问题是我的 while 循环只显示 14 名学生,而我需要它来显示所有 15 名学生。我相信当我使用时,第一个学生正在迷失:
$faculty= result->fetch_assoc();
但是我认为因为我的while
循环正在调用原始$result
数组,所以我不会受到此影响。
谁能解释一下这里发生了什么?如何两次使用同一个数组,而不必重新查询我的数据库,也不会丢失第一个结果?
发生这种情况是因为每次调用fetch_assoc
时,它都会返回当前行并将指针移动到下一行。您可以使用 data_seek
将结果指针调整为结果中的任意行:
$result->data_seek(0);
您的代码将如下所示:
$faculty= $result->fetch_assoc();
if ($faculty['field'] == 1)
die();
$result->data_seek(0);
while($students = $result->fetch_assoc()) {
/*display all students*/
}
我希望这对你有帮助。
您根本不需要将结果放入 faculty 变量中。
$qry = "SELECT * FROM Table WHERE...";
$result = $db->query($qry);
$if($db->error)die($db->error);
// Check to see if Result is Empty
if(mysql_num_rows($result) == 0) {
echo("No Information in Result");
} else {
while($row = mysql_fetch_array($result) {
//Do Some Code Here
//display students with $row variable
echo($row['student_name'] . "<br />");
echo($row['student_age']);
}
}