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

时间:2016-04-04 18:12:43

标签: php mysql insert foreign-keys

I have 2 tables, users and syssla where syssla_id is a foreign key in 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. 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?

2 个答案:

答案 0 :(得分:0)

You should write a stored procedure that inserts first into syssla and then get the id using LAST_INSERT_ID() function to then insert new record into users

答案 1 :(得分:0)

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. so you will never get the wrong id by some other query being executed by a different user.

ps. try and use prepared statements, they protect you better against sql injection than escaping variables manually