简体   繁体   中英

getting all posts the user has liked from database

I am trying to get all the posts the user has liked displaying and not all posts.

I have database tables as follows:

likes (columns (int): likeID, likeBy, likeOn)

posts (columns: postID, postBy, text, likeCount)

users (Columns: userID, username)

Here is my code to get the users liked post (at the moment it gets all liked posts on database and not user liked posts)

public function likes($user_id, $num){

    $stmt = $this->pdo->prepare("SELECT * FROM `likes`, `posts`, `users` WHERE `likeOn` = `userID` and `user_id` = `postBy` ORDER BY `likeOn` DESC");

    $stmt->bindParam(":num", $num, PDO::PARAM_INT);
    $stmt->execute();
    $tweets = $stmt->fetchAll(PDO::FETCH_OBJ);

any ideas on how to get the posts liked by the user and not all liked posts?

As others have said in comments, your schema is not structured in a proper way to have solid relations between tables.

But, given your current structure (and assuming you are updating the likes count, and that posts.postBy contains the user id), you could try something like:

SELECT posts.* FROM posts AS p WHERE COUNT(p.likeCount) > 0 AND p.postBy = the_user_id_variable

If you need posts only, and the userId is contained inside the post row, you do not need to join different tables.

I think this will work.

I changed your query so the statement will return the posts and likes coupled together with the inner join

public function likes($user_id, $num){

    $stmt = $this->pdo->prepare("SELECT * likes INNER JOIN posts ON likes.likeOn = posts.postID WHERE likes.likeBy = ? ORDER BY `likeOn` DESC");
    $stmt->bind_param("i",$user_id);
    $stmt->bindParam(":num", $num, PDO::PARAM_INT); // Don't know what this does 
    $stmt->execute();
    $tweets = $stmt->fetchAll(PDO::FETCH_OBJ);
}

Edit: removed the User table from the query because the userid allready existed in the like table (likeBy).

select p.postID from posts p inner join likes l on l.likeOn=p.postID inner join users u on u.userID = l.likeBy;

我认为上面的查询将为您工作,在MySQL数据库中尝试一下。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM