我有两个表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");
答案 0 :(得分:3)
在执行第二个准备好的声明之前,您不应该发出回复。如前所述,您没有在第二个查询中正确调用LAST_INSERT_ID
,但无论如何您都不需要它。你的代码看起来应该更像这样:
$comments_id = $conn->lastInsertId();
$query = "INSERT INTO news_comments_tbl(news_id_fk, comments_id_fk) VALUES (?, ?)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $newsidfk, PDO::PARAM_INT);
$stmt->bindParam(1, $comments_id, PDO::PARAM_INT);
$stmt->execute();
答案 1 :(得分:0)
看起来你忘记了LAST_INSERT_ID()
要收到此类错误的通知,请在连接后使用此命令启动PDO:
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );