3

I have two tables like so

subscribers

id    subscriber     subscribe_to
1       user1          user2
2       user2          user3
3       user1          user2
4       user3          user4
5       user1          user2
6       user1          user7
7       user5          user2
8       user8          user9
9       user1          user10

And my other table like so: main

id    by_user      post_name
1     user1        somename1
2     user2        somename2
3     user1        somename3
4     user3        somename4
5     user3        somename5
6     user1        somename6
7     user2        somename7
8     user3        somename8

I want to use php-mysql to get all the subscriptions of user1 (for example) from table 1. And then pull the common name from table 2 but I am not sure how to fetch the second table

$get_subscriptions = mysql_query("SELECT * FROM `subscribers` WHERE `subscriber` = 'user1'");
if(mysql_num_rows($get_subscriptions) == 1){
$fetch = mysql_fetch_assoc($get_subscriptions);
$subscriptions = $fetch['subscribe_to'];//this will return an array with all the subscribed to users by user1
} 

Now, I want to fetch the second table and get all the post_name (from $subscriptions). I am not sure how to write the query.

$get_posts= mysql_query("SELECT * FROM `main` WHERE....");
4
  • The thing you're looking for is called a JOIN. Commented Dec 26, 2012 at 5:57
  • 1
    it should be if(mysql_num_rows($get_subscriptions) >= 1) Commented Dec 26, 2012 at 6:00
  • Is there any relationship between these two tables? And Do you want all posts from main table on the bases of subscriber or subscriber_to or something else? Commented Dec 26, 2012 at 6:03
  • yes, when user1 subscribe to user2, I want to start showing the posts of user2 to user1. Commented Dec 26, 2012 at 6:06

2 Answers 2

3

Try this:

SELECT post_name FROM main 
WHERE by_user = 'user1' OR by_user IN (SELECT subscribe_to FROM subscribers WHERE subscriber = 'user1')
Sign up to request clarification or add additional context in comments.

Comments

0
$get_posts = mysql_query("SELECT * FROM `main` WHERE by_user IN ('" . implode("', '", $subscriptions) . "')");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.