Jump to content

[SOLVED] mysql_insert_id ..... in just one query


jonniejoejonson

Recommended Posts

I am inserting a new row into a table that has an auto increment index.

However (only sometimes) I want to use the incremented index value as another value in the row being inserted.

 

eg.

 

i am inserting into table

 

id   name    original_id     message

 

however sometimes i want the original_id to have the same value as my unknown auto-increment id.

 

Is there a way to do this in one sql statement or do i have to:

 

 

eg:

 

1/ sql to insert new row

$valueId=mysql_insert_id();

2/ sql to update inserted row so that original_id=$valueId

 

can this not be done with just one sql statement?

thanks to any responders.

Link to comment
Share on other sites

I don't believe it can be done, because the initial INSERT query has to be completed for the initial auto_increment value to be generated. A possible workaround, though somewhat sloppy, would be to have the original_id value default to NULL unless you provide a value. Then, whenever you query that table, you can us an if null comparison to return the auto_increment value instead of the null.

 

So, to do the data as you require will take the two steps, but there are workarounds that may not require you to use two queries every time.

 

**EDIT**

One other thought would be to set them all to NULL when you want the auto_increment value represented and have a CRON job that runs every X number of minutes or hours and updates them all at once:

UPDATE table_name SET original_id = id WHERE original_id IS NULL;

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.