• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 518
  • Last Modified:

php mysqli - getting results with for loop


I'm just wondering how I can retrieve data using mysqli using a for loop and foreach loop rather than using a while statement. I heard or read somewhere that while is a little slower.

I have this bit of code:
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT name, email FROM freecd WHERE email LIKE ? LIMIT 5")) {

    $stmt->bind_param("s", $code);
    $code = "vkim%";


    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);

    /* close statement */
} else {

      echo $mysqli->error;

Victor Kimura
Victor Kimura
  • 2
2 Solutions
Ray PaseurCommented:
The "while" is not slower.  Use it!
Ray PaseurCommented:
Now having said that let me expand on the answer a little bit.

The while iterator is designed for EXACTLY what you want to do with SQL results sets - to iterate over the data.

The speed of your server is roughly 100,000,000 times faster than a motivated typist.  it will never be possible to find the optimization of "while" if you make measurements in human terms (and I don't know of other terms that matter very much).

You can spend a lot of energy optimizing the wrong thing.  If you do even ONE query in your lifetime that uses a WHERE clause on an unindexed column, you will have lost all the time you might have gained by trying to make "while" faster.  In other words, the performance of "while" is a red herring.

Best wishes for the new year, ~Ray
I doubt very much that the for is faster, but if you really want a for loop:

 for ( ; $stmt->fetch(); ) {
        printf("%s %s\n", $col1, $col2);
Victor KimuraAuthor Commented:
Thank you.

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now