简体   繁体   中英

Query to pull data from mysqli table

I created a database of users, posts and friends and want to pull all post from posts where account_name is $u = "logged in user" and also where account_name is ​"in the friends list of logged in user"

​How can i add the query to pull sth like that? Please check query bellow:

 ​$sql = "SELECT p.*, u.avater FROM posts AS p 
    LEFT JOIN users AS u ON u.username = p.author 
    WHERE (p.account_name='$u') OR (p.account_name = '(if exist in logged_user friends list')  
    ORDER BY p.postdate DESC LIMIT 20";

One way to accomplish this would be to use IN and then select a subquery in your WHERE statement, see below.

I'm not sure of your table structure in logged_user , but simply select one column ( id , in the example below) and then use the $u user in the WHERE statement.

Note, it's bad practice to include the '$u' directly in the query, and you should be using prepared statements.

SELECT p.*, u.avater 
FROM posts AS p 
LEFT JOIN users AS u ON u.username = p.author
WHERE p.account_name = '$u'
OR p.account_name IN (SELECT user2 FROM friends WHERE user1 = '$u')
ORDER BY p.postdate DESC LIMIT 20

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