循环遍历 PHP 准备好的 SQL 语句结果两次

Looping through PHP prepared SQL statement result twice

我试图在 PHP 中遍历 SQL 结果两次,但我没有成功。我尝试过使用 mysqli 数据搜索,但这不起作用。

这是我目前尝试过的方法:

我的新-file.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();
?>

如果我执行下面的代码,我会得到想要的结果:

我的更新-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...]
?>

resources/inefficient 必须 运行 执行和 bind_result 语句两次似乎是一种浪费。我假设 mysqli 数据搜索会将指针重置为 0,我可以再次循环查询。

这可能只是我的疏忽。我做错了什么?

尝试使用 $result->store_result(); 在第一个 $result->execute().

之后

似乎对我有用。