stevieontario Posted May 1, 2013 Share Posted May 1, 2013 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 More sharing options...
stevieontario Posted May 1, 2013 Author Share Posted May 1, 2013 ... and how I became an "advanced member" is beyond me -- unless I automatically got promoted due to seniority (I think I joined this group a few years ago)... Link to comment https://forums.phpfreaks.com/topic/277496-for-loop-keeps-iterating-over-last-item/#findComment-1427528 Share on other sites More sharing options...
mac_gyver Posted May 1, 2013 Share Posted May 1, 2013 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, ... ] Link to comment https://forums.phpfreaks.com/topic/277496-for-loop-keeps-iterating-over-last-item/#findComment-1427530 Share on other sites More sharing options...
Barand Posted May 1, 2013 Share Posted May 1, 2013 Your for loop had no completion condition - you tell it to loop while $i is greater than 1000 and, as $i is incrementing, it will always be greater than that value ad infinitum Link to comment https://forums.phpfreaks.com/topic/277496-for-loop-keeps-iterating-over-last-item/#findComment-1427536 Share on other sites More sharing options...
stevieontario Posted May 2, 2013 Author Share Posted May 2, 2013 thanks everyone -- yes I wrote the loop so it would endlessly repeat. I've rewritten, everything is good. Thanks again! Link to comment https://forums.phpfreaks.com/topic/277496-for-loop-keeps-iterating-over-last-item/#findComment-1427736 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.