'Extracting data from the 2nd table by looking at the condition in a table with php
In my table named Follow, there is the information of those who are followed. For example, let's say my user id is 1:
tableID | followerID | followedID
___________________________________
1 | 1 | 13
2 | 1 | 32
In this table, I follow users with 13 and 32 user IDs.
I have a table named story. In this table, there are blog posts written by each user. Now I want to see the blogs of my users that I follow on the homepage.
storyID | userID | storyDesc
___________________________________
1 | 1 | Lorem Ipsum
2 | 13 | Dolor set
3 | 32 | lorem ipsum dolor sit amet
Normally I can do this as follows:
$connect=$db->preparea("SELECT * FROM story");
$connect->execute();
while($story = $connect->fetch(PDO::FETCH_ASSOC){
$con=$db->prepare("SELECT * FROM follow where followerID='1' and
followedID='{$story['userID']}'");
$con->execute();
$count = $con->rowCount();
if($count == 1){
echo $story['storyDesc'];
}
}
Can I do this directly from the sql query?
Solution 1:[1]
I don't know if this is the right thing to do, but I tried something like this and it worked:
$connect=$db->prepare("SELECT * FROM story RIGHT JOIN follow ON story.userID=follow.followedID where follow.followerID='{1}'");
$connect->execute();
while($result = $connect->fetch(PDO::FETCH_ASSOC)){
echo $result['storyDesc'];
}
Thank you for helping:)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dovletmammet Geldiyev |
