remove results of 1 query that appear in another - php

I have a query that retrieves the name of each friend a user has by joining that of friends and users tables. I have another table that stores active users. I need to retrieve friends that are active and not active but for some reason I am drawing a blank. If I have a list of all friends and a list of active friends, can I subtract active from all to be left with offline? All I Want to do basically is have two tabs. Under one will be offline friends. Under the other will be online friends. If anyone has any useful suggestions, I would appreciate it.
$sql = 'SELECT * FROM users
LEFT JOIN friendships
ON friendships.friend_id = users.id
WHERE friendships.user_id = ?';
$stmt5 = $conn->prepare($sql);
$result=$stmt5->execute(array($userid));
$count=$stmt5->rowCount();
//user has more than 0 friends
if ($count>0){
while ($row = $stmt5->fetch(PDO::FETCH_ASSOC)) {
$online=htmlspecialchars( $row['username'], ENT_NOQUOTES, 'UTF-8' );
//check whos online
$sql = 'SELECT * FROM active_users
WHERE username=?';
$stmt7 = $conn->prepare($sql);
$result=$stmt7->execute(array($online));
$count=$stmt7->rowCount();
while ($row = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$activeuser=$row['username'];
}
}
This code just retrieves active users but hopefully gives an idea of structure.

Could you do a "not in" clause? Without knowing the layout of your database, I'm thinking something like this:
SELECT * FROM users
LEFT JOIN friendships
ON friendships.friend_id = users.id
WHERE friendships.user_id = ?
AND users.id NOT IN (
SELECT user_id FROM active_users
)

Using SQL to do this 'not in' is probably the best solution.
You could also do this in code if you really want to if the results are ordered. Just loop through the all users list, grab the first result from the active users list, and whenever there's a match, put that on the active users list and grab the next active user. Put every non-match into the inactive users list and only fetch from the all users list.
Something like this might tell you both lists in one shot:
SELECT users.username, active_users.username AS active FROM users
LEFT JOIN friendships
ON friendships.friend_id = users.id
LEFT JOIN active_users ON users.username = active_users.username
WHERE friendships.user_id = ?
Inactive users would return NULL in the active columns, where active would not.

Related

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?
select p.postID from posts p inner join likes l on l.likeOn=p.postID inner join users u on u.userID = l.likeBy;
I think the above query will work for you try it in MySQL database.
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).

LEFT JOIN MySQL and PHP

I want to get some statitics out for my adminpanel.
I have two tables named users and cms_prosjekt. I want to count how many projects
that have the same attribute as users.
Each user have a motto that is connected to a project.
For example: Motto is spirit and the project code is spirit. It won't return anything. I have two users with the same motto as code in a project.
<?php
$result = mysql_query("SELECT
users.id,
COUNT(users.motto) AS count
FROM
users
LEFT JOIN cms_prosjekt ON
users.motto=cms_prosjekt.code
GROUP BY
users.motto");
$num_rows = mysql_num_rows($result);
echo "$num_rows";
?>
The query should be count(*) and group by user.motto
"SELECT
user.motto
, COUNT( * ) AS count
FROM users
LEFT JOIN cms_prosjekt ON users.motto=cms_prosjekt.code
GROUP BY users.motto"
The group by should be users.id not users.motto :
<?php
$result = mysql_query("SELECT users.id, COUNT(users.motto) AS count FROM users LEFT JOIN cms_prosjekt ON users.motto=cms_prosjekt.code GROUP BY (users.id)");
$num_rows = mysql_num_rows($result);
echo $num_rows;
?>
Note : i can't see any value for the left join you don't need any data from cms_prosjek but i keep it if you will use it later
I found the solution, but now I want to add a specific user id to the query. Since every administrator have their own home area, I want to list all the users that is connected to a specific administrator. Each administrator is creating projects with users.
I tried this:
$result = mysql_query("SELECT users.motto, COUNT( * ) AS count FROM users
WHERE id = '".$_SESSION['user']['id']."'
LEFT JOIN cms_prosjekt ON users.motto=cms_prosjekt.code
GROUP BY users.motto");

Simple sql multi-table query

I am programming a chat room on my site but I am really new to php. I want users to be able to chat with the users that played in the same teams of a game (knowing that users can have participated together to differents team) and who work in the same area.
Assume there are three tables : the account user's table, the area's t able, games'table
I have a function that returns my query that looks like
function myfunction($userid){
$games_user=mysql_query('select theme from games where games.userid="'.$userid.'"');
$games_theme = mysql_fetch_array($games_user);
$sql = ("select userid, username, area.userid
from account
left join area
on account.userid = area.userid
left join games
on account.userid = games.userid
where account.userid <> '".mysql_real_escape_string($userid)."' and '".(in_array(games.theme,$games_theme))."' and area.userid=1
);
return $sql;
}
Reformatted:
$sql = "
SELECT userid, username, area.userid
FROM account
LEFT JOIN area ON account.userid = area.userid
LEFT JOIN games ON account.userid = games.userid
WHERE account.userid <> '".mysql_real_escape_string($userid)."'
AND '".(in_array(games.theme,$games_theme))."'
AND area.userid = 1
";
But it really doesn't work, I think I have syntax problems.
I don't really understand how in_array is indexed, and I don't know how to do in a simpler way that query
Can anybody help ?
I'm still not entirely sure what you are doing, but I think this is what you want; you can do this in a single query:
<?php
function myfunction($userid){
$id = mysql_real_escape_string($userid);
$sql = "SELECT userid, username, area.userid
FROM account
LEFT JOIN area
ON account.userid = area.userid
LEFT JOIN games
ON account.userid = games.userid
WHERE account.userid<>'$id' AND area.userid=1
AND games.theme IN (SELECT theme FROM games WHERE games.userid='$id')
";
return $sql;
}
?>

mysql return the total of rows for each user_id

$sql = "SELECT * FROM books LEFT JOIN users
ON books.readby=users.user_id WHERE users.email IS NOT NULL";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['readby']. " - read 10 books";
} //while ends
this is the code I have so far. I am trying to retrieve the number of books read by each user
and echo the results. echo the user_id and number of books he/she read
books table is like this : id - name - pages - readby
the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.
A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.
Edit The GROUP BY had been omitted...
SELECT
users.*,
usersread.numread
FROM
users
/* join all user details against count of books read */
LEFT JOIN (
/* Retrieve user_id (via readby) and count from the books table */
SELECT
readby,
COUNT(*) AS numread
FROM books
GROUP BY readby
) usersread ON users.user_id = usersread.readby
In your PHP then, you can retrieve $row['numread'] after fetching the result.
// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
// don't know the contents of your users table, but assuming there's a
// users.name column I used 'name' here...
echo "{$row['name']} read {$row['numread']} books.";
}
You can use count() this way:
<?php
$count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
$count = $count[0];
?>
Hope this helps! :)

MySQL/PHP - Nested Select Issue - Need To Obtain Values From Both Tables

I just need help refining this script to give me the values from both tables joined on the ID.
Basically I want the ID from both tables and then be able to get the other values from both tables based on the IDs (if need be) and display them in a loop.
The code I have is below but won't work.
$select = myQ("SELECT * FROM users a WHERE EXISTS (SELECT 1 FROM `videos` b WHERE a.id = b.id GROUP BY b.id HAVING count(*) > 1) ");
$i=0;
while ($row = myF($select)) {
$resultsLoopArray[$i]["videos.id"] = $row["id"];
$resultsLoopArray[$i]["videos.vid"] = $row["vid"];
$resultsLoopArray[$i]["users.username"] = $row["username"];
$i++;
}
if (isset($resultsLoopArray)) {
$tpl->Loop("searchResultsLoop", $resultsLoopArray);
}
For now all I need is the username from the users table, the id and video id from the video table.
Can someone help by chance?
you question is bit confusing me..
As for my understanding I am posting this soultion..
If you have two tables users , videos then .
$sql = "SELECT users.username , videos.* from users, videos where users.user_id = videos.user_id";
this query will fetch all record from users and videos table where user id is present in videos tables ...

Categories