简体   繁体   English

如何使用 SET 在 mysql 中创建 LAST_INSERT_ID 用户定义变量?

[英]How do I use SET to create a LAST_INSERT_ID user-defined variables in mysql?

I need to insert values into multiple tables where the primary key ( id ) of the first table (users) is the foreign key ( user_id ) of subsequent tables (email etc.).我需要将值插入多个表中,其中第一个表(用户)的主键( id )是后续表(电子邮件等)的外键( user_id )。

I worked out the following query in MySQL Workbench, which works perfectly fine there.我在 MySQL Workbench 中计算出以下查询,在那里工作得很好。 However when I run it in the context of the website form that I'm developing I keep getting a syntax error message for the line: SET @nameID = LAST_INSERT_ID();但是,当我在我正在开发的网站表单的上下文中运行它时,我不断收到该行的语法错误消息: SET @nameID = LAST_INSERT_ID();

INSERT INTO users (first_name, last_name)
  VALUES('John', 'Doe');
SET @userID = LAST_INSERT_ID();
INSERT INTO email (user_id, email)
  VALUES(@userID,'johndoe@email.com');
INSERT INTO phone_number (user_id, phone_number)
  VALUES(@userID, 4546254758);

I've spent a bit of time trying to workout what the issue is but haven't been able to come with an answer so far.我花了一些时间试图弄清楚问题是什么,但到目前为止还没有得到答案。 Any help would be appreciated.任何帮助,将不胜感激。

Edit: Updated code to show that by 'multiple' I mean more than two.编辑:更新代码以显示“多个”是指两个以上。

You don't need a user variable for this.为此,您不需要用户变量。 If you are running the two queries sequentially in the same database session, you can just do:如果您在同一个数据库会话中按顺序运行这两个查询,则可以执行以下操作:

INSERT INTO users (first_name, last_name)
  VALUES('John', 'Doe');
INSERT INTO email (user_id, email)
  VALUES(LAST_INSERT_ID(),'johndoe@email.com');

don't run all queries one shot , you should run one by one then it will work through php normally , try like this不要一次运行所有查询,你应该一个一个运行,然后它会通过php正常工作,像这样尝试

    $mysqli = new mysqli('localhost', 'root', '', 'test');
    $mysqli->query("INSERT INTO users (first_name, last_name)
       VALUES('John8', 'Doe');" );
    $mysqli->query('SET @userID = LAST_INSERT_ID();' );
    $mysqli->query("INSERT INTO email (user_id,email) VALUES ( @userID 
       ,'johndoe8@email.com');" );

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

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