Joining two tables and check if record exist - php

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"

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).

select * that match user postcode in mysql table?

I'm trying to display a list of users who live locally to the user who is logged in. so if the logged in session user has a postcode of 'm3 4' and 5 other users have a postcode beginning with 'm3 4' then these users will be shown to the user.
My table is laid out like this:
id | user_id | user_postcode
1 2 M3 4
2 3 SM2 7
3 4 M3 4
so in this scenario user 2 will be shown to user 4 who is logged in because their post codes match.
I'm trying to do this in mysql and it works when i put the postcode in manually like so:
AND ptb_stats.user_postcode='M3 4'
but I'm trying to make it user session specific, so if the logged in user / $_SESSION[user_id'] has the same post code as other users.
i'm trying to do it this way, but it's showing all the users without postcodes where as it should be showing the users that have matching postcodes, shouldn't it?
function get_local_users() {
global $connection;
global $_SESSION;
$query = "
SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode='".$_SESSION['user_postcode']."'";
$local_set = mysql_query($query, $connection);
confirm_query($local_set);
return $local_set;
}
With this answer, I assume that the $_SESSION['user_postcode'] is filled from some type of input box and the value is a valid zipCode (like "M3 4").
You can use preg_match to split the zipcode from the number and try to select zipcodes form the db. Take a look at this example:
$matches = array();
$zipCode = preg_match('/^([a-z0-9]+)/i', $_SESSION['user_postcode'], $matches);
The zipcode is now in the $matches variable at the second place ($matches[1]).
Now use this value to create a query and check if it is the same as others..
$query = "SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode REGEX '^" . $matches[1] . "'";
According to what you describe, I will go onto something like that.
I used prepared statement from PDO to handle the query.
function get_local_users() {
// given that it was created like this: $connection = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
global $connection;
$stmt = $connection->prepare(
"SELECT ptb_stats.*
FROM ptb_stats, ptb_users
WHERE ptb_stats.user_id = ptb_users.id
AND ptb_stats.user_id != ?
AND ptb_stats.user_postcode = (
SELECT user_postcode
FROM ptb_stats
WHERE user_id = ?
)");
$stmt->execute(array($_SESSION['user_id'], $_SESSION['user_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
If the user id is stored in $_SESSION['user_id'], you can get the local users with
select u.id, u.name
from ptb_users u
join ptb_stats s1 on s1.user_id = $_SESSION['user_id']
join ptb_stats s2 on s2.user_id = u.id and s2.user_postcode = s1.user_postcode
where u.id <> $_SESSION['user_id']
SQLFiddle
If you have the postcode in $_SESSION['user_postcode'], it is even easier
select u.id, u.name
from ptb_users u
join ptb_stats s on s.user_id = u.id
and s.user_postcode = $_SESSION['user_postcode']
where u.id <> $_SESSION['user_id']
SQLFiddle

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 ...

remove results of 1 query that appear in another

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.

Categories