Jump to content


Photo

for loop and sql queries


  • Please log in to reply
6 replies to this topic

#1 Tandem

Tandem
  • Members
  • PipPipPip
  • Advanced Member
  • 251 posts

Posted 29 August 2006 - 12:18 AM

I'm trying to use a for loop to insert records into my database. Here's some theoretical code:

for ($i = 0 ; $i < $num ; $i++) {
$id = mysql_insert_id();
$do_insert = mysql_query("INSERT INTO BLAH (ID) VALUES('$id')");
}

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.

#2 olegk

olegk
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 29 August 2006 - 12:23 AM

because you are trying to insert identical IDs into the table. I assume ID is the primary key.

#3 Tandem

Tandem
  • Members
  • PipPipPip
  • Advanced Member
  • 251 posts

Posted 29 August 2006 - 12:30 AM

Yes it is. How would you suggest i insert different id's?

#4 Corona4456

Corona4456
  • Members
  • PipPipPip
  • Advanced Member
  • 244 posts
  • LocationEl Paso, TX

Posted 29 August 2006 - 12:44 AM

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:

mysql_query("INSERT INTO BLAH (ID) VALUES (NULL)

What is the CoronaMatrix?

#5 Tandem

Tandem
  • Members
  • PipPipPip
  • Advanced Member
  • 251 posts

Posted 29 August 2006 - 12:49 AM

Ahhh, ok thanks Corona, that's exactly what i needed.

#6 Corona4456

Corona4456
  • Members
  • PipPipPip
  • Advanced Member
  • 244 posts
  • LocationEl Paso, TX

Posted 29 August 2006 - 01:26 AM

No Problem... glad to help :)
What is the CoronaMatrix?

#7 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,025 posts

Posted 29 August 2006 - 06:39 AM

Also, you call mysql_insert_id() AFTER the insert to find out the value of the newly allocated id.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users