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
https://forums.phpfreaks.com/topic/277496-for-loop-keeps-iterating-over-last-item/
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, ... ]

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.