通过PHP循环编写两次SQL语句结果

时间:2015-04-03 14:11:56

标签: php arrays loops mysqli while-loop

我试图在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...]
?>

两次运行execute和bind_result语句似乎浪费资源/效率低下。我假设mysqli数据搜索会将指针重置为0,我可以再次遍历查询。

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

提前感谢您提供任何输入/解决方案。

- 安东尼

1 个答案:

答案 0 :(得分:2)

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

之后

似乎为我做了伎俩。

/安德斯