Tandem Posted August 29, 2006 Share Posted August 29, 2006 I'm trying to use a for loop to insert records into my database. Here's some theoretical code:[code]for ($i = 0 ; $i < $num ; $i++) {$id = mysql_insert_id();$do_insert = mysql_query("INSERT INTO BLAH (ID) VALUES('$id')");}[/code]when i do this, only 1 record is inserted, no matter what the value of $num ($num is always a posive number above 0 btw).What should i do to make it insert the right numbr of records?If you don't understand me or need more info just say.Any help appreciated. Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/ Share on other sites More sharing options...
olegk Posted August 29, 2006 Share Posted August 29, 2006 because you are trying to insert identical IDs into the table. I assume ID is the primary key. Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/#findComment-81955 Share on other sites More sharing options...
Tandem Posted August 29, 2006 Author Share Posted August 29, 2006 Yes it is. How would you suggest i insert different id's? Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/#findComment-81957 Share on other sites More sharing options...
Corona4456 Posted August 29, 2006 Share Posted August 29, 2006 If your ID field is auto_increment then you don't have to worry about it... don't give it a value and MySQL will do it for you or you can pass it null... as follows:[code]mysql_query("INSERT INTO BLAH (ID) VALUES (NULL)[/code] Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/#findComment-81962 Share on other sites More sharing options...
Tandem Posted August 29, 2006 Author Share Posted August 29, 2006 Ahhh, ok thanks Corona, that's exactly what i needed. Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/#findComment-81966 Share on other sites More sharing options...
Corona4456 Posted August 29, 2006 Share Posted August 29, 2006 No Problem... glad to help :) Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/#findComment-81976 Share on other sites More sharing options...
Barand Posted August 29, 2006 Share Posted August 29, 2006 Also, you call mysql_insert_id() AFTER the insert to find out the value of the newly allocated id. Link to comment https://forums.phpfreaks.com/topic/18959-for-loop-and-sql-queries/#findComment-82032 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.