Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jun 2010
    Posts
    278
    Thanks
    63
    Thanked 8 Times in 8 Posts

    How to loop through returned rows?

    Hi all,

    I want to be able to loop through a set of rows returned from a query and insert data into another table based on the result. I can do this in PHP but is there a way of doing it with pure MySQL?

    Here's an example of what I'd do in PHP:

    PHP Code:
    $result myQueryFunction("select x from table1 where y = 3");  //Returns a 2D array of results, for the sake of argument.

    foreach ($result as $row)  //Now do something (doesn't matter what) with x in each row and store the result.
      
    myQueryFunction("insert into table2 set z = ".myOtherFunction($row["x"])); 
    So can I do that in pure MySQL?

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    3,763
    Thanks
    23
    Thanked 548 Times in 547 Posts
    INSERT INTO table2 (z)
    SELECT table1.x FROM table1
    WHERE table1.y = 3

    Backup Your stuff before trying. It works for my DB.

  • Users who have thanked sunfighter for this post:

    XmisterIS (12-07-2011)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •