[英]Looping through PHP prepared SQL statement result twice
我试图在 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();
?>
如果我执行下面的代码,我会得到想要的结果:
我的更新文件.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,并且我可以再次循环查询。
这可能只是我的疏忽。 我究竟做错了什么?
尝试使用$result->store_result();
在第一个$result->execute().
似乎对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.