简体   繁体   English

选择上一个插入ID

[英]Select last insert id

I am inserting a record and i want to use the id of the last record inserted. 我正在插入一条记录,我想使用插入的最后一条记录的id。 This is what i have tried: 这是我尝试过的:

    $sql = 
    'INSERT INTO customer
(first_name,
last_name,
email,
password,
date_created,
dob,
gender,
customer_type)
VALUES(:first_name,
:last_name,
:email, 
:password, 
:date_created, 
:dob, 
:gender, 
:customer_type)' . ' SELECT LAST_INSERT_ID()' ;

I am getting the error: 我收到错误:
You have an error in your SQL syntax; 您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()'. 检查与MySQL服务器版本对应的手册,以便在'SELECT LAST_INSERT_ID()'附近使用正确的语法。 Can anyone show me where is my mistake? 任何人都可以告诉我我的错误在哪里? Thanks! 谢谢!

Check out mysql_insert_id() 看看mysql_insert_id()

mysql_query($sql);
$id = mysql_insert_id();

When that function is run after you've executed your INSERT statement in a mysql_query() command its result will be the ID of the row that was just created. 在mysql_query()命令中执行INSERT语句后运行该函数时,其结果将是刚刚创建的行的ID。

You can do another query: 你可以做另一个查询:

$last_id = "SELECT LAST_INSERT_ID()";

Or try to add ; 或者尝试添加; in your query: 在您的查询中:

INSERT INTO customer (first_name, last_name, email, password, date_created, dob, gender, customer_type) VALUES(:first_name, :last_name, :email, :password, :date_created, :dob, :gender, :customer_type)<b>;</b>' . ' SELECT LAST_INSERT_ID()';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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