1

I used query like this

INSERT INTO coins VALUES (NULL, '$user_ID', '$title', NOW())

now later in this same script page, I need to use value coin_ID that I just inserted in the query above. It's auto increment value so I added NULL.

how can I use this coin_ID in this same page, after I ran some checking with PHP?

thanks

2
  • and I forgot to mention, I'm going to use that coin_ID to select linked columns in another table Commented Feb 20, 2012 at 17:44
  • I get this error when I use that function i.imgur.com/f34EJ.png can it be issue with permissions? Commented Feb 20, 2012 at 17:55

6 Answers 6

2

mysql_insert_id in PHP or LAST_INSERT_ID in mysql

Sign up to request clarification or add additional context in comments.

Comments

2

It depends on which database driver you are using with PHP. If you are using the standard mysql functions you can use the mysql_insert_id function:

$coin_id = mysql_insert_id()

If you are using PHP's PDO then you can use the lastInsertId() method:

$coin_id = $DB->lastInsertId()

If you are using a database that supports the RETURNS sql keyword (such as postgres) then you can do it in one query. MySQL doesn't support it however.

INSERT INTO coins VALUES (NULL, '$user_ID', '$title', NOW()) RETURNING coin_id;

If you edit your post to include the method of database interaction that you are using, we can provide a more specific answer.

Comments

2

See mysql_insert_id.

Comments

1

Use mysql_insert_id to retrive last inserted ID.

Comments

1

$coin_ID = mysql_insert_id();

Comments

0

Try using LAST_INSERT_ID() via the PHP mysql_insert_id function.

4 Comments

Is this function actually safe in the face of there being another thread/process that INSERTs into the database between when the current context inserts, and then runs this function? If not, seems like that'll lead to subtle corruptions/errors that are very hard to track down!
@Kitsune LAST_INSERT_ID is safe in a transaction, and mysql_insert_id is always safe (for PHP code which doesn't share a single DB connection between threads). See stackoverflow.com/questions/1808337/… .
@Kitsune please don't take mysql developers as complete fools.
@Col.Shrapnel It has nothing to do with taking them for fools, but of exactly what that function does. According to that other question, if the same connection is shared among multiple threads and transactions are not used, it WILL return the wrong data in the scenario I outlined. That's important information to have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.