我有这两个表comments_tbl 和news_comments_tbl,我正在使用MySQL。
当我创建评论时,我想将最后创建的评论 ID 发送到新表 news_comments_tbl 中。
在使用准备好的语句之前,我使用了这种方法,并且效果很好:
//comment
$name = $_POST['name'];
$comment = $_POST['comment'];
//ID
$commentidfk = $_POST['comments_id'];
$newsidfk = $_POST['news_id_fk'];
$newsidfk = $_GET['news_id_fk'];
if (isset($_POST['comment']))
{
$sqlquery ="INSERT INTO comments_tbl(comments_id, name, comment)
VALUES (NULL, '$name', '$comment')";
$result = $conn->query($sqlquery) or die('Error');
$sqlquery2 ="INSERT INTO news_comments_tbl(news_id_fk, comments_id_fk)
VALUES ('$newsidfk', LAST_INSERT_ID())";
$result2 = $conn->query($sqlquery2) or die('Error');
header("location:news.php");
}
else
{
echo 'Error';
}
但是现在当我转换为使用 PDO 准备好的语句时,我无法让它工作。评论已创建,但我无法将最后插入的 id 插入新表(news_comments_tbl)
这就是我的做法:
$query = "INSERT INTO comments_tbl(comments_id, name, comment) VALUES (NULL,?,?)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1,$name, PDO::PARAM_STR);
$stmt->bindParam(2,$comment, PDO::PARAM_STR);
$stmt->execute();
return $conn->lastInsertId('comments_id');
$query = "INSERT INTO news_comments_tbl(news_id_fk, comments_id_fk) VALUES (?, LAST_INSERT_ID)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $newsidfk, PDO::PARAM_INT);
$stmt->execute();
header("location:news.php");