在INSERT(PHP)中将2个不同的查询合并为一个

时间:2017-12-30 07:23:15

标签: php mysql sql

我有两张桌子,他们是

name
- fname
- sport_id (FK)

sports
- id (PK)
- football
- basketball

所以我为INSERT

做了这个
mysqli_query($mysqli, "INSERT INTO name(fname)
    VALUES('$fname')");
mysqli_query($mysqli, "INSERT INTO sprots(football, basketball)
    VALUES('$football','$basketball')");

是正确的吗?或者我应该将它们合并到一个查询中?关系和身份怎么样?

2 个答案:

答案 0 :(得分:3)

您需要首先将数据插入sports表,然后从sports表中获取最后插入的ID,然后插入名称表

获取最后插入的ID

mysqli_query($mysqli, "INSERT INTO sports(football, basketball) VALUES('$football','$basketball')");

$last_id = mysqli_insert_id($mysqli); 

mysqli_query($mysqli, "INSERT INTO name(fname,sport_id ) VALUES('$fname','$last_id')");

答案 1 :(得分:1)

正如评论中所建议的那样:

// Insert into sports table
mysqli_query($mysqli, "INSERT INTO sports(football, basketball)
    VALUES('$football','$basketball')");

// Get last inserted id (in sports table)
$sport_id = mysqli_insert_id($mysqli);

// Insert it into name table
mysqli_query($mysqli, "INSERT INTO name(sport_id,fname)
VALUES('$sport_id','$fname')");