0

Is it possible to get the insert id that is going to be inserted in a query?

So for example, is there something that could do something like:

$stmt = $cxn->prepare("INSERT INTO numbers (new_id) VALUES (?)");
$stmt->bind_param('i', GET_ID_BEING_INSERTED());
$stmt->execute();

Thanks.

Bagwell
  • 2,018
  • 5
  • 18
  • 24

2 Answers2

3

Yes, you can query:

SELECT last_insert_id()

to fetch the ID of the last inserted dataset, but you should do it right after your insert operation.

The result will be provided in a column named last_insert_id()

SquareCat
  • 5,699
  • 9
  • 41
  • 75
  • That's not what I need. I'm trying to use the insert id to insert it into the database all in one query. – Bagwell Dec 15 '13 at 02:04
  • 1
    Ah, i get you now! [See this thread](http://stackoverflow.com/questions/6761403/how-to-get-the-next-auto-increment-id-in-mysql) – SquareCat Dec 15 '13 at 02:04
1

The PHP function mysql_insert_id() retrieves the ID generated for an AUTO_INCREMENT column by the previous query.

m59
  • 43,214
  • 14
  • 119
  • 136
turkeyhundt
  • 214
  • 1
  • 15