1

Possible Duplicate:
php/MySQL insert row then get 'id'

How can I do get current ID number with INSERT INTO?

mysql_query("INSERT INTO mytable(id,a,b) VALUES(null,3,current ID) ");

mysql_query("
    INSERT INTO tablo(id,a,b)
    VALUES(null,3,this ID number)
            ^            ^
            |            |
            | <Copy ID>  |
            |____________|
");
Community
  • 1
  • 1
Ayhan DELİ
  • 37
  • 1
  • 6
  • what do you mean under current id? where is this insert into query run? Be more specific – rsz Oct 03 '12 at 17:08
  • 2
    He means he wants to do an insert SQL and get the id back, he doesn't know what it is since he passes in null. Here's the answer http://stackoverflow.com/questions/897356/php-mysql-insert-row-then-get-id – Eric Leschinski Oct 03 '12 at 17:09
  • My question is distorted during recording. fixed it. – Ayhan DELİ Oct 03 '12 at 17:30

3 Answers3

4

Use mysqli_insert_id(), which returns the auto-generated id used in the last query.

Read "PHP mysql_insert_id() Function" or "mysql_insert_id".

Example:

<?php
$query= "INSERT INTO table_name VALUES ('a','b','c')";
$result = mysql_query($query);
echo "INSERT statement ID is" . mysql_insert_id();
?>

And do read the big red box in the PHP documentation on the mysql_insert_id page, starting with mysqli.

See the PHP Documentation For further reference.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • I'm trying but don't work, mysql_query("INSERT INTO tablo (id,a,b) VALUES(null,5,mysql_insert_id())"); I don't want MySQLi. I want to MySQL. – Ayhan DELİ Oct 03 '12 at 17:18
  • You really don't want to use `mysql_query` unless you absolutely have to. It's dangerous and much harder to use correctly. – tadman Oct 03 '12 at 17:21
1

Basically you can use the mysqli_insert_id function.

As stated in the PHP manual:

The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

Bruno Vieira
  • 3,884
  • 1
  • 23
  • 35
0

You can try to get the next value of the sequence used in the selected table. Please check if MySQL has any function to get this value. If you need to have this number while executing a SQL statement, then using a PHP function is impossible.

Check "Get Auto Increment value with MySQL query".

Community
  • 1
  • 1
Pawel
  • 407
  • 1
  • 6
  • 14