我将数据插入到这样的表中:
$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();
}
ALTER TABLE likes
ADD PRIMARY KEY (`post_id`, `user_id`)
现在我希望我的声明表现的是,当$ statement1因PK而失败时退出执行。
我希望很清楚我想要什么,任何人都可以提供帮助。谢谢!
答案 0 :(得分:0)
我打算引用你 -
“现在我希望我的陈述行为是什么,退出执行时 由于PK,$ statement1失败。“
在这种情况下,如果:
if($statement1->rowCount() < 1){
//quite execution
}
BTW:你在使用PDO时正在进行类似mysql的查询。所以,这一行:
$queryInsertUserLike = "INSERT INTO likes (user_id, post_id) VALUES ($userId, $id)";
应该参数化,例如:
$queryInsertUserLike = "INSERT INTO likes (user_id, post_id) VALUES (?, ?)";
然后execute
使用..
execute(array($_SESSION['userid'], $id)
)