Search code examples
phpmysqlmysqlidev-to-production

MySQLi returns an object but won't return results in foreach loop


I have a basic MySQLi query that is returning a MySQLi object and looping through it in a foreach(); to display a dump of data from my db. When I test it locally running PHP 5.5.9 everything is fine but when I put it on my remote production server running PHP 5.3.3 it will return the object in a var_dump but it will not loop through the results and display them.

Here is the code:

if ($mysqli->connect_errno) {
echo "There was an error";
     } else {

          if ($result = $mysqli->query("SELECT * FROM acronyms")) {

     }
       else {

    echo "query error";

     }

     foreach($result as $x=>$y) {
         echo $y["definition"];
     }
}       

?>

It appears that mysqli is installed on my production server but just won't loop in an identical file that have in my testing server.

I have also rewritten the query in regular MySQL and have been able to get the data out of the database.


Solution

  • You need to actually do something with the results like use fetch_assoc() to interate through the results.

    $mysqli = new mysqli("localhost", "name", "pw", "db");
    
    if ($mysqli->connect_errno) {
      echo "There was an error";
    }
    else {
    
      if ($result = $mysqli->query("SELECT * FROM acronyms")) {
      }
      else {
        echo "query error";
      }
    
      while ($row = $result->fetch_assoc()) {
        echo $row["definition"];
      }
    
    }
    

    Note the while ($row = $result->fetch_assoc()) { which is a fairly standard method used to roll through MySQLi results like this.