PHP Foreach on MySQLi Result set

14,064

Solution 1

Do this instead:

if ($result = $mysqli->query('DESCRIBE ' . $table)) {
    $columnCount = 0;
    echo '<ul>';

    /* fetch associative array */
    while ($field = $result->fetch_assoc()) {
        if (in_array($field["Field"], $sheetData[0])) {
            echo "<li>$field[Field] - $field[Type]</li>\r\n";
            $columnCount++;
        }
    }

    echo '</ul>';

    /* free result set */
    $result->free();
}

Solution 2

So since I asked this question ages ago I figure I should update it with some additional clarification by saying this: what I did first with the foreach loop does work. The caveat being that it only works in PHP 5.4+ as that's when the mysqli_result class implemented the Traversable interface. This means you can iterate over it using a foreach loop in later versions of PHP.

This change apparently wasn't super well-known at the time I posted my question (mid-2013) likely due to the fact that so many servers across the internet still use 5.3--likely because that's the latest version of PHP available to Ubuntu 12.x--which limits its utility to recently updated servers. But when you're in an environment that supports it this is a totally valid technique to use.

Share:
14,064
moberemk
Author by

moberemk

I'm just a kid trying to figure out this whole "computers" thing. Except I get graded on it which automatically makes it 20% less fun.

Updated on June 18, 2022

Comments

  • moberemk
    moberemk almost 2 years

    I have this chunk of code which works on my local XAMPP testing server. The problem is, when pushed to the production server, it breaks. This isn't an issue with the database connection, and PHP/MySQL are both at 5.3 on the production server so it isn't the use of old versions of either. I'm thinking it's the use of the foreach loop instead of the more standard while loop; if it's that, why?

    <?php
       $res = $mysqli->query('DESCRIBE '.$table);
       $columnCount = 0;
       echo '<ul>';
       foreach($res as $field) {
         if(in_array($field["Field"], $sheetData[0])) {
          echo '<li>';
                //var_dump($field);
          echo $field['Field'].' - '.$field['Type'];
          echo "</li>\r\n";
          $columnCount++;
        }
      }
      echo '</ul>';
    ?>
    

    EDIT: To clarify, it breaks by not outputting anything at all; when inserting a simple echo statement inside the loop, it seems to not even execute it.

    EDIT2: I've added an answer below which goes into slightly more detail about what the problem here actually was and why this code does actually work under certain conditions.