【发布时间】:2015-06-08 15:22:26
【问题描述】:
我试图在 PHP 中循环遍历 SQL 结果两次,但没有成功。我曾尝试使用mysqli数据搜索,但这不起作用。
这是我迄今为止尝试过的:
我的新文件.php
<?php
class myClass {
function myFunction() {
/*--Connection file for MySQL database. This file works fine.--*/
include $_SERVER['DOCUMENT_ROOT'] . "connection-files/mysqli-connect.php";
if ($result = $mysqli->prepare($query)) {
$result->execute();
$result->bind_result($var1, $var2, $var3);
/*============================================================*/
/*====If I take out all of the code between the = signs, my second while statement works=====*/
$myArray = array();
while ($result->fetch()) {
if (!in_array($var1, $myArray)) {
array_push($myArray, $var1);
}
}
/*--I thought the line below would reset looping through the query.--*/
$result->data_seek(0);
/*====If I take out all of the code between the = signs, my second while statement works=====*/
/*============================================================*/
/*--The second while statement is not echoing anything.--*/
while ($result->fetch) {
echo $var1;
}
}
}
}
$newClass = new myClass;
$newClass->myFunction();
?>
如果我执行下面的代码,我会得到想要的结果:
my-newer-file.php
<?php
[...All prior code from before...]
while ($result->fetch()) {
if (!in_array($var1, $myArray)) {
array_push($myArray, $var1);
}
}
/*--I thought the line below would reset looping through the query.--*/
$result->data_seek(0);
/*--Executing and binding the results again seems to get the second while statement to work, but running the execution statement twice seems inefficient.--*/
$result->execute();
$result->bind_result($var1, $var2, $var3);
/*--This now works because of the above two lines--*/
while ($result->fetch) {
echo $var1;
}
}
}
}
[...All prior code from before...]
?>
必须运行两次execute 和bind_result 语句似乎浪费资源/效率低下。我假设mysqli数据搜索会将指针重置为0,我可以再次循环查询。
这可能只是我的疏忽。我做错了什么?
【问题讨论】:
-
您是否尝试在第一个 while 语句之前编写
$result2=$result,然后在第二个 while 语句中使用$result2而不是$result? -
注意
while循环!虽然还有结果,请获取它们,当循环完成时,没有更多的结果要获取,即使是第二个循环也没有,这是你永远不需要的。 -
为什么你不能用 1 个循环来完成这个?
-
@Mathematician171 - 感谢您的输入。那仍然需要我运行两次结果语句。
-
@adeneo - 感谢您的意见。我了解 while 循环是如何工作的,但我的问题是关于为什么 mysqli 数据搜索不会重新启动指向 SQL 结果中第一行的指针,这正是它的用途。
标签: php arrays loops mysqli while-loop