0

Can i combine these two queries in one single query that will check if user already liked one particular post, and if not then insert data.

In first query i check if row with that user id and and that post id exists

$existCheck = $con->prepare("SELECT * FROM likes WHERE user=:user AND post=:post");
$existCheck->execute(array(':user'=>$user_id, ':post'=>$post_id));
$existNumber = $existCheck->rowCount();

And in second query i insert data if row doesn't exist

if($existNumber == 0) { 
    $insertLike = $con->prepare("INSERT INTO likes (user, post) VALUES(:user, :post)"); 
    $insertLike->execute(array(':post'=>$post_id, ':user'=>$user_id));
}

And $user_id = $_SESSION['user_id']; and $post_id is unique id of each post.

This is my table structure enter image description here

Nenad Vracar
  • 102,378
  • 14
  • 116
  • 136
  • 2
    Read [url1](http://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql) and [url2](http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table) – Saty Oct 27 '15 at 10:12
  • Referring to the link finds a solution to your question, [Stackoverflow](http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table) – sanjeev shetty Oct 27 '15 at 10:15
  • Did you try your headline in any search engine? – syck Oct 27 '15 at 10:18
  • Thanks for suggestions, i did read those questions and i did try googling it but i couldn't figure out answer, but i will read it again few more times. This is just for learning purposes. – Nenad Vracar Oct 27 '15 at 10:24

1 Answers1

0

You need to set your user and post fields as unique

ALTER TABLE `likes` ADD UNIQUE (`user`, `post`)

And then use one single sql:

INSERT INTO likes (user, post) VALUES(:user, :post) ON DUPLICATE KEY UPDATE `id`=`id` /* Hack to ignore updating */
  • Is this going to work because one user can vote on multiple posts so same user_id can be repeated multiple times same goes for post_id because different users can vote on same post so user_id can be repeated in likes table. Only when same user want to vote on same post then i don't want to insert. – Nenad Vracar Oct 27 '15 at 10:53
  • Yes. This will work. In my case you set unique group of params, not one param. And if you added `user`=1, `post`=1 and then add `user`=1, `post`=2 or `user`=2, `post`=1 this will be unique groups of values. But if this group wouldn't be unique "UN DUPLICATE KEY UPDATE " statement will process – Andrey Telesh Oct 27 '15 at 11:39