Sql将id从一个表插入到另一个表中

时间:2017-11-23 02:54:21

标签: php mysql sql

我的数据库中有两个表。当我将记录插入第一个表时,我需要使用由Mysql自动生成的id并将其添加到第二个表中的新记录中。

所以我需要从这条记录中取id

$sql = "INSERT INTO movies (title, year, format);

并将其放入此记录中:

$sql = "INSERT INTO actors(name, last_name, movi_id);
-----------------------------------------------^
                                              HERE

1 个答案:

答案 0 :(得分:1)

使用下面的内置PHP函数从上一个Insert Query中获取id:

mysqli_insert_id();

您的代码必须如下所示才能解决您的问题:

$sql = "INSERT INTO movies (title, year, format) VALUES ($title, $year, 
$format)";    
$movi_id = mysqli_insert_id();
$sql = "INSERT INTO actors(name, last_name, movi_id) VALUES ($name, 
$last_name, $movi_id)";

如果您可以在准备好的语句中写上述查询以使其更加安全,那就更好了:

// prepare and bind Movies Query
$queryMovies = $conn->prepare("INSERT INTO movies (title, year, format) 
VALUES (?, ?, ?)");
$queryMovies->bind_param("sss", $title, $year, $format);

// execute Movies Query
$queryMovies->execute();

// Get last inserted Id of Movies Query
$movi_id = $queryMovies->insert_id;

// prepare and bind Actors Query
$queryActors = $conn->prepare("INSERT INTO actors (name, last_name, movi_id) 
VALUES (?, ?, ?)");
$queryActors->bind_param("sss", $name, $last_name, $movi_id);

// execute Actors Query
$queryActors->execute();

// Close Connections
$queryMovies->close();
$queryActors->close();