简体   繁体   English

如何将数据插入一个表并获取主键作为外键插入另一个表中?

[英]How do I insert data into one table & get the primary key to insert in another table as a foreign key?

I have 2 tables, users and syssla where syssla_id is a foreign key in users(syssla_id2) . 我有2个表,用户和syssla,其中syssla_id是users(syssla_id2)的外键users(syssla_id2)

create table syssla(                                    
    syssla_id int auto_increment,
    Uppgift varchar (255),
    Information text,
    Tid varchar(100),
    primary key(syssla_id)
)engine=innodb;

create table users(                                 
    user_id int ,
    username varchar (50),
    user_password varchar (50),
    Namn varchar(100),
    syssla_id2 int,
    primary key(user_id),
    foreign key(syssla_id2) references syssla(syssla_id)
)engine=innodb;

I want to do an insert with a form in php . 我想在php使用表单进行插入。 But how can I do to get the foreign key to be inserted to a specific user in the other table(users) at the same time? 但是如何才能将外键同时插入到其他table(users)中的特定用户?

您应该编写一个首先插入syssla的存储过程,然后使用LAST_INSERT_ID()函数获取id,然后将新记录插入users

You do the following: 您执行以下操作:

// you start a mysql transaction
$mysqli->begin_transaction();
// execute your first query
$mysqli->query(""); // Insert query here
$new_id = $mysqli->insert_id;

$mysqli->query(""); // second query here using the $new_id

$mysqli->commit();

$mysqli->close();

If for whatever reason the second query fails it will cancel the first query and it will be like nothing ever happened, also starting a transaction prevents other queries from overwriting you last inserted id. 如果由于某种原因第二个查询失败,它将取消第一个查询,它将像没有发生任何事情,也开始一个事务阻止其他查询覆盖您上次插入的ID。 so you will never get the wrong id by some other query being executed by a different user. 所以你永远不会通过其他用户执行的其他查询得到错误的id。

ps. PS。 try and use prepared statements, they protect you better against sql injection than escaping variables manually 尝试使用预处理语句,它们可以更好地保护您免受sql注入,而不是手动转义变量

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

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