View Full Version : How to loop through returned rows?

12-07-2011, 10:52 AM
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:

$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?

12-07-2011, 02:59 PM
INSERT INTO table2 (z)
SELECT table1.x FROM table1
WHERE table1.y = 3

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