我将数据插入到这样的表中:
$queryUpdatePosts = "UPDATE posts SET likes = likes + 1 WHERE id = $id";
error_log('user: '.$_SESSION['userid'].' post '.$id);
$userId = $_SESSION['userid'];
$queryInsertUserLike = "INSERT INTO likes (user_id, post_id) VALUES ($userId, $id)";
try {
$db -> beginTransaction();
$statement1 = $db -> prepare($queryInsertUserLike);
$statement1 -> execute();
$statement2 = $db -> prepare($queryUpdatePosts);
$statement2 -> execute();
$row = $statement -> fetch();
$db -> commit();
} catch (Exception $e) {
$db -> rollback();
}
在“LIKES”表中,user_id 和 post_id 被定义为这样的主键
ALTER TABLE likes
ADD PRIMARY KEY (`post_id`, `user_id`)
现在我希望我的语句表现的是,当 $statement1 由于 PK 失败时退出执行。
我希望很清楚我想要什么,并且任何人都可以提供帮助。谢谢!