簡體   English   中英

循環通過 PHP 准備的 SQL 語句結果兩次

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM