简体   繁体   中英

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?

You are probably looking for the mysql_insert_id function :

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

Or mysqli_insert_id or PDO::lastInsertId , depending on which extension you use to access your MySQL database.

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());
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM