Search code examples
phpmysqldatabaseinsertlastinsertid

How to get the value of id(primary key) in previous operation in MySQL


I am using MySQL. I need to insert one row into a table first, then I need to get the id of the inserted row. The code looks somewhat like the following:

insert into mytable (column2, column3, column4) values('value2','value3','value4')or die(mysql_error());

Column1

is the

primary key

and it is auto-increment. So how to get the value of

column1

in the previous operation?


Solution

  • You can use mysql_insert_id. From the docs:

    <?php
    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('mydb');
    
    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf("Last inserted record has id %d\n", mysql_insert_id());
    ?>