• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 521
  • 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 KimuraSEO, Web DeveloperAuthor Commented:
Thank you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

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