PHP MYSQL Query Loop Results with FOREACH Possible?

7 replies
While, DO While, For Loops work very well for iterating results from a MYSQL database call whether you use the older MYSQL or the new MYSQLI method to retrieve the data, doesn't matter.

The question I have, is it possible to get database results using a FOREACH loop?

I have only been able to retrieve ONE record via foreach loop and for some reason it is the second record. I don't know why.

Here is the code I have been playing with:

It gets one field from all records in a table. Doesn't matter really but I just chose one field instead of ALL for testing.

PHP Code:

$qry 
"SELECT member FROM warriors";
         
$rsWar mysql_query($qry$db) or die(mysql_error());
          
//$rslt     = mysql_fetch_assoc($rsWar);
          
$sum   mysql_num_rows($rsWar);
            
            
foreach(
$rsWar as $v){
                echo 
$v;

         }
         
foreach(
$rsWar as $k=>$v){
                echo 
$k." -> ".$v;

         }

foreach(
mysql_fetch_array($rsWar) as $v){
                echo 
$v;

         }
         
foreach(
mysql_fetch_assoc($rsWar) as $v){
                echo 
$v;

         } 
I tried list and each as well but either php exploded or my IDE bugged out on the code above.

FOREACH is designed to iterate through arrays... MYSQL returns results in arrays... Why then can FOREACH NOT be used to parse through mysql results?

Depending how you write the query and send it to MySQL you can get all the results in one go.

While loops, for loops, do while works fantastic but FOREACH sucks for retrieving database data. Why is that?

Anyone able to get FOREACH to work for this?

I could do it by adding a for loop inside the foreach but defeats the purpose when I can just use a for loop.

Any thoughts?
#foreach #loop #mysql #php #query #results
  • Profile picture of the author Nail Yener
    Hi Terry,

    I use foreach frequently to display data from the database. But to display all the items, you need to retrieve all the items first by using a while loop (or something like that). Here is a sample:



    For some reason I cannot paste PHP code into my posts.

    I hope that helps.
    {{ DiscussionBoard.errors[5037789].message }}
  • Profile picture of the author SteveJohnson
    The function mysql_query returns a resource - not the actual data. You must use the 'fetch' functions to retrieve the individual rows.

    The 'foreach' construct is merely a way to iterate through arrays or objects, and is a way of combining 'list' and 'each' for working with arrays.

    I would highly recommend using an addon class like ezSQL ( available at Justin Vincent , or used to be ) to work with databases. It makes programming life so much easier. As a matter of fact, ezSQL is what the WordPress database functions are derived from.
    Signature

    The 2nd Amendment, 1789 - The Original Homeland Security.

    Gun control means never having to say, "I missed you."

    {{ DiscussionBoard.errors[5044220].message }}
    • Profile picture of the author DEaFeYe
      Banned
      [DELETED]
      {{ DiscussionBoard.errors[5045313].message }}
      • Profile picture of the author SteveJohnson
        Originally Posted by DEaFeYe View Post

        [code]
        You guys and your silly PHP
        Exactly how does this add any value to the thread? I don't see an answer to the question in the OP.
        Signature

        The 2nd Amendment, 1789 - The Original Homeland Security.

        Gun control means never having to say, "I missed you."

        {{ DiscussionBoard.errors[5045785].message }}
        • Profile picture of the author DEaFeYe
          Banned
          [DELETED]
          {{ DiscussionBoard.errors[5045918].message }}
          • Profile picture of the author mojojuju
            Originally Posted by DEaFeYe View Post


            Use Django.
            It's obvious from this and some of your other posts that you're a Django zealot/fanboy. Good for you. Django is nice. Many people use and enjoy it. I've dabbled in it. Very good stuff.

            But where you extol the virtues of Django, pretty much of what you think is super duper about Django could be said of using a web application framework in general. Whether it be a python framework, or a PHP framework, or a rails framework, or whatever ...

            Others gave answers within the context of the OP's question (PHP MYSQL Query Loop Results with FOREACH Possible?). You did not. You instead decided to evangelize for Django - a python framework, when the OP was asking a question related to PHP.

            It's understandable that you want badly for everybody to love Django. You use it. You love it. You want others to use and love it. I love Pepsi, but I'm not going to interject into every Coca-cola discussion because of it.

            There's plenty of frameworks out there that will get the OPs job done. But because he's not using one, I don't see the point of using his question as an opportunity to evangelize any particular framework.

            Django (or any framework) may be better suited to the OPs task. But we don't know what he's trying to accomplish overall. Perhaps he's modifying an existing PHP application, trying to add/change a basic functionality, in which case adding code relevant to a python framework isn't going to help him much.

            Sometimes it's nice to just answer peoples questions.

            Anyhow, I hope I made it clear what's so annoying about the "OMG, you guys should use Django! Django is a hammer!" comments.
            Signature

            :)

            {{ DiscussionBoard.errors[5046155].message }}
            • Profile picture of the author DEaFeYe
              Banned
              [DELETED]
              {{ DiscussionBoard.errors[5046350].message }}
              • Profile picture of the author mojojuju
                Originally Posted by DEaFeYe View Post

                It's funny, because the other thread you're clearly referring to is where I suggested Perl would be a better tool for the job.

                Would you like me to link it up?
                No, you don't have to. If I recall correctly, there was a topic regarding some simple task involving using regular expressions in PHP. As if PHP or any language wasn't capable of such a simple task, you thought that perl should be used instead.
                Signature

                :)

                {{ DiscussionBoard.errors[5046563].message }}
  • Profile picture of the author Terry Crim
    You guys are weird.

    Off the top of my head here, I think it is

    PHP Code:
    WHILE( = mysql_fetch_assoc()) 
    OR is it just

    PHP Code:
    WHILE(mysql_fetch_assoc() 
    either way.. the proper version of this WHILE statement WORKS..
    Do this same exact thing with a FOREACH and it FAILS miserably...

    I was just curious why foreach fails while a FOR, WHILE and DO While Loops work perfectly in the OP scenerio.

    I wasn't necessarily asking how to get data out of a database, I already have that covered I was just curious like I said about why foreach vs the other loops etc..

    I pretty much got it covered and went back to working. Thanks for those that contributed answers and thoughts.

    Nail, Thanks for the code sample, I pretty much was doing something similar but a part of your sample triggered a insight which took me into a few different directions. Ended up shrinking two massive functions down to one multiple option function which ended up giving me more compact code but also gave better results.

    I also spent some time creating an auto form creation script which will save me a lot of time down the road which came from a question I had during the process of figuring out a few other things. LOL

    Anyway, thanks all.

    I can't think of the name of the platform I was using before, one of the well known ones but some reason the name escapes me now. I took a look through it's source code once and the ways they had things coded to make their "shortcuts" work was a freaking nightmare..

    PLUS you had to code to THEIR way of doing things and some interesting results came from certain situations that I couldn't account for why their code would produce that result in the way it got it. It wasn't wrong but holy crap to get the result.. no wonder most of these back end platforms REQUIRE so many optimizations and helper systems to a standard mysql and server setup..

    Sure you can save time coding using these helper systems but for me, it was just easier to go back to hard coding a 4 or 7 line while, if structure than use these helper systems. At least with what I was and am doing. They have their place but if u rely on them too much your going to have some issues down the road in situations where the scope of a project doesn't require such systems..

    That and I found some very interesting licensing to more than a few code contributions to a number of these systems. Another issue there, the legal stuff, I didn't want to get into trouble down the road there with selling anything I created so again another reason I went back to coding the old school way.

    Thanks guys,

    - T
    {{ DiscussionBoard.errors[5046240].message }}
  • Profile picture of the author Terry Crim
    I don't know why most of my post above turned green. I Hope it is still readable if not that's cool, just makes me sound weird if it isn't..

    I edited the post to break up one long run on paragraph which I actually added lines but didn't show up for some reason in the final post. Using the quick edit feature might not be that great an idea for long posts. LOL
    {{ DiscussionBoard.errors[5046272].message }}

Trending Topics