Search code examples
phpmysqlfacebook-like

How can I delete a like from my database if user_id and post_id are the same?


I want to check if user already liked the post, if so than delete the user from database likes.

I've tried to do an if statement but it wont get to the else and only add likes even when user_id and post_id are the same.

Like.class.php

private function Addlike(){
                $conn = db::getInstance();
                $query = "insert into likes (post_id, user_id) values 
                (:post_id, :user_id)";
                $statement = $conn->prepare($query);
                $statement->bindValue(':post_id',$this->getPostId());
                $statement->bindValue(':user_id',$this->getUserId());
                $statement->execute();
            }
        private function Deletelike(){
                $conn = db::getInstance();
                $query = "DELETE FROM likes WHERE post_id = :post_id 
                AND user_id =:user_id";
                $statement = $conn->prepare($query);
                $statement->bindValue(':post_id',$this->getPostId());
                $statement->bindValue(':user_id',$this->getUserId());
                $statement->execute();
        }

        public function CheckLike(){
                $conn = db::getInstance();
                $query = "SELECT COUNT(*) FROM likes WHERE 
                post_id=:post_id AND user_id=:user_id";
                $statement = $conn->prepare($query);
                $statement->bindValue(':post_id',$this->getPostId());
                $statement->bindValue(':user_id',$this->getUserId());
                $statement->execute();
                $result = $statement->fetchAll(PDO::FETCH_ASSOC);
                if($result["COUNT(*)"] == 0){
                    $this->Addlike();
                }else{
                    $this->Deletelike();
                }
                return $result;
        }

If you press like for the first time you should like the post and it should be stored in the database, if you press again you unlike the post and it gets deleted from the database. But now it only does the Addlike function...


Solution

  • I think PDO::FETCH_ASSOC returns a multidimensional array when used with PDOStatement::fetchAll, according to https://www.php.net/manual/en/pdostatement.fetchall.php#refsect1-pdostatement.fetchall-examples.

    Try changing your code to something like this and see if it works. You could also try dumping the $result variable to see what the structure looks like.

    if($result[0]["COUNT(*)"] == 0){
        $this->Addlike();
    }else{
        $this->Deletelike();
    }
    

    If an array index doesn't exist, PHP considers it false, which would explain why you're always adding likes, since false == 0 in PHP.

    If you want to avoid this equivalency of false and 0, use the identical operator to also compare types:

    if ($result["COUNT(*)"] === 0) {
    ...