Im trying to find an efficient way to display all posts from people who are being followed by the logged in account holder.
There are two key tables:
1- Posts
table name : posts
id, account_name, published, body
2- Follows
Table name : follows
id, account_name, followed_name
I'm trying to find a way that i can display all the posts from all the accounts that are being followed. The connection between Posts and Follows is the Account_name.
I understand that it will probably be a join, but it's how I construct the WHERE clause. So far I have the following (The account name is set via $_SESSION['account_name']):
$sql = "SELECT * FROM posts LEFT JOIN follows ON posts.account_name = follows.account_name WHERE --- How would I only get the posts from the accounts being followed ?---"
I'm sure this is something simple my brain just feels drained and I cant seem to work it out.
UPDATE Attempting in PDO
Returning NULL at the moment,
$sql = "SELECT * FROM share_posts WHERE account_name IN (SELECT followed_name FROM $this->account_follows WHERE account_name = :account_name)";
return $this->AC->Database->select($sql, array('account_name' => $account_name));
The goes to my Database Class:
public function select($sql, $array = array(), $fetch_mode = PDO::FETCH_ASSOC)
{
$stmt = $this->AC->PDO->prepare($sql);
foreach ($array as $key => $value)
{
$stmt->bindValue("$key", $value);
}
$stmt->execute();
return $stmt->fetchALL($fetch_mode);
}
The returned data is NULL at the moment even though the logged in account has followed other accounts.
$account = $_SESSION['account_name'];
//do some sql injection checking on $account here
$sql = "SELECT * FROM posts WHERE account_name IN (SELECT followed_name FROM follows WHERE account_name='".$account."')";
This will get all the posts where the account name matches somebody you follow. I wasnt sure who was following who, but in this case the followed_name are the people account_name is following. If thats the other way around, switch the values
$sql = "SELECT * FROM posts WHERE account_name IN (SELECT account_name FROM follows WHERE followed_name='".$account."')";
I will write this the way I interpret your question.
What you need to do is select only the posts from the users that are followed by your logged in user.
To break this down, first you want to select the users followed by the logged in user. To do this, we use the Follows table.
We then want to select the posts by these users. As such my query would be this.
SELECT posts.* FROM follows
LEFT JOIN posts ON posts.account_name = follows.follows_name
WHERE follows.account_name = $logged_in_user
Related
I have to try two joins but this is not going to work.
code in Codeginator.
$this->db->select('concat(firstName," ",lastName) as fullnameVisitor,users.firstName,visitorId,destinationId,count,activityStatus,created,updated');
$this->db->from('interestedprofile');
$this->db->join('users','users.userId=interestedprofile.visitorId','LEFT');
$this->db->join('users','users.userId=interestedprofile.destinationId','LEFT');
$this->db->join('interestedprofile','interestedprofile.destinationId=users.userId','LEFT');
$this->db->order_by('created','desc');
return $this->db->get()->result_array();
User Table : https://i.stack.imgur.com/ppM3s.png
Interest Table : https://i.stack.imgur.com/EbQIX.png
i have to find visitedid and destinationid users firstName and lastName in Users Table.
You don't have to use the Active Record fully to do the joins. You can use regular SQL. For example,
$query = $db->query("SELECT * FROM users;");
foreach ($query->getResult('User') as $user)
{
echo $user->name; // access attributes
echo $user->reverseName(); // or methods defined on the 'User' class
}
This Code is Work For me.
Select us1.firstName,us2.firstName from interestedprofile ip join users us1 on us1.userid = ip.visitorId join users us2 on us2.userId = ip.destinationId
I have two tables:
users - Where gender information is stored:
id
username
gender
user_thoughts- Where all posts are stored:
id
added_by
What I am trying to do is determine how many posts have been made by male and female users separately. But I am just completely stumped on how to achieve this. So far, I have the following:
<?php
include ("connect.php");
// updating table posts_by_gender whenever admin logs in.
// 1.Get gender of user to compare against the author or the thought
$get_all_users_gen = mysqli_query ($connect, "SELECT gender FROM users WHERE account_type = 'user'");
while ($getting_gen = mysqli_fetch_assoc ($get_all_users_gen)){
$gender = $getting_gen['gender'];
// 2. Get all posts
$getting_thoughts = mysqli_query ($connect, "SELECT username FROM user_thoughts");
$getting_th = mysqli_fetch_assoc ($getting_thoughts);
$added_by = $getting_th['added_by'];
} // while closed
?>
I am just completely confused on what to write after this.
Summary:
Trying to check each row in user_thoughts table, get the added_by data (which is the same as username from users table) and see if that user is male or female.
At the end of the check, I need a variable which holds a number of how many posts belong to male users, and how many to female.
You can do this with a Join... An example given below
SELECT * FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
This will get all user thoughts by male... Then you can do a mysqli_num_rows($query) to get the count.
You can do the same for females...
However, if you only need the count, it may be adviseable to run
SELECT COUNT(*) AS number FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
and this would return the number of rows directly.
I know this question is very common on Stack, but I can't seem to find an answer or a snippet of code that actually solves my problem...
I have two tables, accounts and orders. I want to write a SQL statement to pull Order ID, Date, Total and Status from orders, and also Username from accounts.
The statement would be something like this:
$ohsql = "select * from orders where Username = '". $login_session ."'";
Obviously Username will come from the accounts table, but the principal is there. I am missing the join as I am clueless about it!
You need to 'link' the two tables. For that do something like :
- add a column accountid to Orders table; so this tells us, which order belongs to which user . We then use this info in our JOIN.
Easy way to do it in 2 queries :
// get the id value of the username
$id = select id from accounts table where username = $login_session
// use that in the JOIN
select * from orders JOIN accounts ON orders.accountid = accounts.id where accounts.id = $id
Assuming that your orders table contains the accountId and your accounts table containing the user name use following query
$ohsql = "select o.*, a.username from orders o
INNER JOIN accounts a ON a.id = o.accountId
WHERE a.username = '". $login_session ."'";
Let me know if you face any issue
I'm trying to make a social network; I have a table for users' posts.
The table looks like:
id fromuid touid date ip content
fromuid is the user who posted the post, and touid is set to whoever you post to. So if you go on someone's page and make a post, touid is set to your UID. However, if you're home and don't post at any one touid will be set to your UID.
Now here's my problem: I'm trying to get the content of the users you're following. There's a table like so for followers:
id follower following date
Then, in my post's class, I get all the followers and put them into a predefined array like so:
$getRelatedPostsQuery = new Database();
$getFollowers = $getRelatedPostsQuery->query(array("SELECT * FROM follower WHERE follower = ?", array($this->uid)))->fetchAll(PDO::FETCH_ASSOC);
foreach ($getFollowers as $key) {
$followers[] = $key['following'];
}
This is where I begin to struggle. I have this query here:
$getRelatedPosts = new Database();
$relatedPostsResult = $getRelatedPosts->query(array("SELECT * FROM posts WHERE fromuid IN ('". implode("', '", $followers) ."') ORDER BY id DESC", array()))->fetchAll(PDO::FETCH_ASSOC);
This works absolutely fine, but the problem is, if for example I follow a user called Jack, and a user I'm not following, say, Jill, posts on Jack's wall, I'll see what Jill posted. I obviously want to only see the content of the users I have followed. How would I best go about doing this? Also, I'm guessing this is probably an over-complicated way of doing this, yes? Any suggestions would be greatly appreciated.
If I'm understanding you correctly, you're wanting all the posts from only those people whom you're following, and not posts by other people to those that you're following.
If that's the case, a simple addition to your where clause should do the trick:
$relatedPostsResult = $getRelatedPosts->query(array("SELECT * FROM posts WHERE fromuid IN ('". implode("', '", $followers) ."') AND fromuid = touid ORDER BY id DESC", array()))->fetchAll(PDO::FETCH_ASSOC);
This will tell the query to only grab the posts where fromuid is the same as touid (posts where the person posted on their own "wall").
You also asked if there is a simpler way to do it, and there is if you combine the queries:
$getRelatedPosts = new Database();
$relatedPostsResult = $getRelatedPosts->query(
array("SELECT * FROM posts WHERE fromuid IN(SELECT fromuid FROM follower WHERE follower = ?) AND fromuid = touid ORDER BY id DESC",
array($this->uid))
)->fetchAll(PDO::FETCH_ASSOC);
Or if you'd rather use a join:
$getRelatedPosts = new Database();
$relatedPostsResult = $getRelatedPosts->query(
array("SELECT * FROM posts, follower WHERE follower.follower = posts.fromuid AND follower.follower = ? AND follower.fromuid = follower.touid ORDER BY posts.id DESC",
array($this->uid))
)->fetchAll(PDO::FETCH_ASSOC);
You can use a join and you get it in 1 SQL query
You probably have a user table with id field
you have a table posts with fromuid and touid
Use a table follower to make the link between followers and followed with foreign keys (follower and followed, corresponding to user.id) :
follower, followed, date
then you can get all post from people followed by current user with a query like that :
select * from posts
join follower on follower.followed = post.fromuid
where follower.follower = $this->id
I have this table advertisements, where I store all my advertisements. Everytime a user clicks on an advertisement, I record that click into a table called advertisement_clicks.
What I store in both tables is: userid and a unique token.
So, I want to count how many available advertisements there is for the user to see. Currently, I am doing it like this:
$ex = $dbh->prepare("SELECT * FROM advertisements WHERE status='2' AND fixed='0'");
$ex->execute();
foreach ($ex as $normal) {
$search2=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE token=:token AND username=:username");
$search2->bindParam(":token",$normal['token']);
$search2->bindParam(":username",$userdata['id']);
$search2->execute();
}
$allnormal = $ex->rowCount();
$clickednormal = $search2->rowCount();
$normalads = $allnormal-$clickednormal;
$allnormal = how many advertisements is available.
$clickednormal = how many of these advertisements has the user clicked.
So the above approach is a bit messy and it doesn't give the correct result.
Can someone help me do this a smarter way?
You can use COUNT to get it through SQL instead.
SELECT count(*) as addCount FROM advertisement_clicks WHERE
token=:token AND username=:username"
I havn't messed with php in a while so I'm not going to even attempt to write some code lol, but the way I did it was I executed this query:
SELECT COUNT(*) FROM advertisement_clicks WHERE token=:token AND username=:username
Then get the query result which will return the advertisement count.