这段代码有什么问题?我想插入具有相同电影 ID 和不同演员 ID 的多行。当我用 $actors = array(1,2,3,4); 运行它时 (或任何值)和 $movid = 1,所有四行都作为值 (1, 4) 插入。
$create_query = "INSERT INTO `tableName`(`movId`, `actId`) VALUES";
$comma = "";
foreach ($actors as $key=>$value) {
$create_query .= $comma . "(:movie" . $key . ", :actor" . $key . ")";
$comma = ", ";
}
$query = $db->prepare($create_query);
foreach ($actors as $key=>$value) {
echo $movid . ', ' . $value //correct output (1, 1), (1, 2) ...
$query->bindParam(":movie" . $key, $movid, PDO::PARAM_INT);
$query->bindParam(":actor" . $key, $value, PDO::PARAM_INT);
}
print_r($query);
//output is
/*INSERT INTO `tableName`(`movId`, `actId`) VALUES(:movie0, :actor0), (:movie1, :actor1), (:movie2, :actor2), (:movie3, :actor3)*/
if ($query->execute()) {
$return = $query->rowCount();
$query->closeCursor();
}
当我使用单独的查询进行插入时,它可以正常工作。