Skip to content
Advertisement

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. I have tried to use mysqli data seek, but this does not work.

Here is what I have tried so far:

my-new-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();
?>

If I do the code below, I get the desired result:

my-newer-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...]
?>

It seems like a waste of resources/inefficient to have to run the execute and bind_result statements twice. I was under the assumption that mysqli data seek would reset the pointer to 0, and I could loop through the query again.

This is probably just an oversight on my part. What am I doing wrong?

Advertisement

Answer

Try using $result->store_result(); right after the very first $result->execute().

Seemed to do the trick for me.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement