A like/unlike system using MySQL and PDO I have created a Like/Unlike system. The user clicks one to indicate a "like", and clicks again to "unlike" it. Currently I do that like this:

try {                                             -- like
    $stm1 = $db_conn-&gt;prepare("INSERT into votes (post_id, user_id) VALUES (?, ?)");
    $stm1-&gt;execute(array($post_id, $_SESSION['id']));

} catch(PDOException $e){
    if ((int) $e-&gt;getCode() === 23000) {          -- unlike
        $stm2 = $db_conn-&gt;prepare("DELETE FROM votes WHERE post_id = ? AND user_id = ?");
        $stm2-&gt;execute(array($post_id, $_SESSION['id']));

    } else {
        $error = true;
    }
}


Note: $e-&gt;getCode() === 23000 means row is duplicate. because there is a unique index on post_id and user_id columns.

Well my code works as well. Just when a professional programmer see it, he says: your algorithm is wrong and you shouldn't delete something when insert fails (on duplicate).

Well, should I change my current code? What's wrong with it? Trust me it works perfectly :) ..!
This design is a consequence of a poorly designed API. It looks like the client will hit one URL that will cause the like/unlike state to be toggled. But what if the user has multiple tabs open on the same page, then clicks "like" on each one? The user might believe that they are reiterating the "like", when in fact they are undoing it.

My advice is not to toggle the state on the server side. Offer "like" and "unlike" as two separate calls. The client should be responsible for deciding which API to call, based on the client-side state.