[英]Looping through PHP prepared SQL statement result twice
I'm trying to loop through a SQL result in PHP twice, and I am not succeeding.我试图在 PHP 中循环两次 SQL 结果,但没有成功。 I have tried to use mysqli data seek, but this does not work.
我曾尝试使用 mysqli 数据查找,但这不起作用。
Here is what I have tried so far:这是我迄今为止尝试过的:
my-new-file.php
我的新文件.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();
?>
If I do the code below, I get the desired result:如果我执行下面的代码,我会得到想要的结果:
my-newer-file.php
我的更新文件.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...]
?>
It seems like a waste of resources/inefficient to have to run the execute and bind_result statements twice.必须两次运行 execute 和 bind_result 语句似乎是浪费资源/效率低下。 I was under the assumption that mysqli data seek would reset the pointer to 0, and I could loop through the query again.
我假设 mysqli 数据搜索会将指针重置为 0,并且我可以再次循环查询。
This is probably just an oversight on my part.这可能只是我的疏忽。 What am I doing wrong?
我究竟做错了什么?
Try using $result->store_result();
尝试使用
$result->store_result();
right after the very first $result->execute().
在第一个
$result->execute().
Seemed to do the trick for me.似乎对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.