Jump to content

FOR loop keeps iterating over last item


Recommended Posts

Morning Freaks,

 

I can't get the following For loop to stop iterating over the final item. As you can see, I want to put the results of a select MySQL query into another table in the same database.

<?php
for ($i=1000; $i >= 1000; $i++)

		$sql = "SELECT columnB, columnC from table1
     	where columnA = '$i'";
	
		$result = mysql_query($sql, $cxn) or die (mysql_error());
		
			
		while ( $row = mysql_fetch_assoc($result)){	
		extract($row);
}

	$sqlIns = "insert into table2 (columnB,columnC)
		values
		('$columnB', '$columnC' )";
		$t1query = mysql_query($sqlIns);
		error_reporting(E_ALL);


		}
	mysql_close($cxn);
?>

columnA is table1's id field, auto-increment. Table1 has 2000 rows; so the maximum value of columnA is 2000.

 

What happens is the loop just keeps executing, and adding row upon row of the columnB and columnC values where columnA = 2000. I have to kill the darn query to get out of it.

 

I suspect I should be using a break command somewhere, but where?

 

 

Link to comment
Share on other sites

your for(){} loop doesn't have any {} so the only statement being executed inside the loop is the $sql = " ... "; statement and you just end up with the last $sql statement.

 

however, for what you are doing, just use an (one) INSERT ... SELECT query (no loop is required) -

 

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [iGNORE]

[iNTO] tbl_name [(col_name,...)]

SELECT ...

[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.