Search code examples
mysqlsqlinsert-into

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


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>  |
            |____________|
");

Solution

  • 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.