我有两张桌子,他们是
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')");
是正确的吗?或者我应该将它们合并到一个查询中?关系和身份怎么样?
答案 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')");