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).
Related
I'm trying show some records from table and if doesn't exist to show button create new. If exist to show record.
There are two tables - users
user_id
username
...
And restaurants
rest_id
name
menu
So after user is created and he log into his account must have condition if user_id has restaurant user_id = menu (menu from restaurants). If doesn't exist in restaurant show button create. This is the query with which I trying
$q = $pdo->prepare("SELECT * FROM restaurants m
LEFT JOIN users ON users.user_id = m.menu WHERE rest_id = :user_id");
$q->bindParam(':user_id', $_SESSION['user_id']);
$q->execute();
// fetch the results
$results = $q->fetchAll(PDO::FETCH_ASSOC);
if(count($results) > 0) {
foreach($results as $res) {
echo ' '.$res['name'].' ';
}
} else {
echo 'Create New';
}
In this way when user login he see button Create New because he doesn't have one. The problem is when he log again after he is created record already ... button Create New is visible again.
I thing the problem is in the query or no?
UPDATE:
menu row hold user_id from session when he create new one. This is in restAdd.php
$sql = "INSERT INTO restaurants ( name, menu, image) VALUE ( :name, :menu, :image)";
$q = $pdo->prepare($sql);
$q->execute(array(
':name' => $name,
':menu' => $_SESSION['user_id'],
':image' => $forDB
));
Try with this query:
SELECT m.rest_id, m.name FROM restaurants m
INNER JOIN users ON users.user_id = m.menu
WHERE menu = :user_id
1) INNER JOIN instead of LEFT, you want to check if there are restaurants related with the user.
2)I think you did a little mistake, the menu field is wich contains the user id
In this case you need in your where clause menu = :user_id not rest_id = :user_id
Try with this:
SELECT * FROM restaurants m
LEFT JOIN users ON users.user_id = m.menu WHERE menu = :user_id"
I'm attempting to do a relatively simple MySQL query where I return the favorite posts added by the user. However, my only error is the name of the post int he favorites returns as the user who added the favorite and not the actual user who wrote the post. Below is my database for the favorites and then the query below. Please let me know if you need more information from me as I'd be happy to help in any way.
$username = $_GET['username'];
//initial query
$query = "SELECT body, latitude, longitude, (SELECT username FROM Users WHERE Users.IDUser=Favorites.IDUser) AS username, (SELECT profile_picture FROM Users WHERE Users.IDUser=Favorites.IDUser) AS profile_picture, filename, post_date FROM Posts, Favorites WHERE Posts.IDPosts = Favorites.IDPosts AND Favorites.IDUser=(Select IDUser FROM Users WHERE Users.username=:username) ORDER BY post_date DESC";
$query_params = array(
':username' => $username
);
DB diagram:
![enter image description here][2]
You should have uploaded your database schema for this question and you should've formatted your query to be more readable but anyway I don't know if that's correct, I could not tried it but try and please let me know if it is wrong (I don't know what I'm doing because I cannot see the schema and I don't know what are you trying to do)
SELECT body, latitude, longitude, Users.username,
Users.profile_picture, filename, post_date
FROM Posts, Favorites, Users
WHERE Users.username=:username AND Posts.IDPosts = Favorites.IDPosts
AND Favorites.IDUser = Users.IDUser ORDER BY post_date DESC
Edit
SELECT Users.profile_picture, Users.username, latitude,
longitude, post_date, filename
FROM Users
JOIN Posts ON Posts.IDUser = Users.IDUser
JOIN Favorites ON Posts.IDPosts = Favorites.IDPosts
WHERE Users.username=:username
AND Users.IDUser = Posts.IDUser
AND Posts.IDPosts = Posts.IDPosts
$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! :)
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 ...
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.