php - PDO stop execution of transaction on duplicate PK -


i inserting data table this:

$queryupdateposts = "update posts set likes = likes + 1 id = $id"; error_log('user: '.$_session['userid'].' post '.$id); $userid = $_session['userid']; $queryinsertuserlike = "insert 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(); } 

in "likes" table, user_id , post_id defined primary-key this

alter table likes add primary key (`post_id`, `user_id`) 

now want statement behave is, quit execution when $statement1 fails because of pk.

i hope it's clear want , can help. thanks!

i going quote on -

" want statement behave is, quit execution when $statement1 fails because of pk."

in case, if :

if($statement1->rowcount() < 1){    //quite execution   } 

btw: doing mysql-like querying while using pdo. so, line:

$queryinsertuserlike = "insert likes (user_id, post_id) values ($userid, $id)"; 

should parameterized, like:

$queryinsertuserlike = "insert likes (user_id, post_id) values (?, ?)"; 

then execute using..

execute(array($_session['userid'], $id))


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -