php mysql join query on same table using pdo - php

This is my table in which ID is table's primary key and SUPER_ID is used to manage hierarchy for example here, A is super user of B and B is super user of C while A is super-super user of C............
ID AND SUPER_ID MAY NOT NECESSARY BE SEQUENTIAL
Now question is when A is logged in, He can see details of his own and of Both B and C While B is logged in He can see details of His own and C only. And C can see his own details only.
I have written this query:
<?php
$sql="SELECT * from TABLE
WHERE
ID =:loginId OR
ID IN
(
SELECT ID FROM TABLE
WHERE SUPER_ID =:SuperId
)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':logedIn' => $_SESSION['sess_login_id'] , ':SuperId' => $_SESSION['sess_login_id']) );
?>
This query gives me results of A and B when i logged in as User A.
What query should I write so that I can get results of A , B and C when I logged in as User A?
Because A is a super user of B and super-super user of C. Please help. Thank You.

If you have only three hierarchy levels, you can do it like this:
SELECT DISTINCT u.*
FROM user loggedin
LEFT JOIN user children ON children.SUPR_ID = loggedin.ID
LEFT JOIN user grandchildren ON grandchildren.SUPR_ID = children.ID
JOIN user u ON u.ID IN (loggedin.ID, children.ID, grandchildren.ID)
WHERE loggedin.ID = :loginId
http://sqlfiddle.com/#!9/3d93c/7

http://sqlfiddle.com/#!9/ad6a88/2/0
First get SUPR_ID from the user, then check which SUPR_ID is bigger or same.
SELECT * FROM `TABLE` WHERE SUPR_ID >= (SELECT SUPR_ID FROM `TABLE` WHERE ID=:loginId)

Related

Get all the members below me in an mlm module in PHP and MySQL

I have a database, as shown in this, any user can join with any sponsor ID, and they will get their own user ID which can lead the tree further. I want to get details of a particular user_id, say, '2'. I am expecting the output in which the user_id will be (3,4 since 3 is directly linked with 2 and 4 is linked directly with 3 which is linked with 2). Similarly if I select user_id 1, then I would get the resultant user_id (2,3,4,5, where 2 and 5 are directly linked to user_id 1 and 3,4 are indirectly linked to 1).
I have tried almost every possible while loop format, but I just can't get the output. Here is the final bit of my code, because I have deleted most of it:
<?php
include 'config.php';
$current_user='1';
$all = mysqli_query($con,"SELECT * FROM users");
while($all_array = mysqli_fetch_array($all)){
$all_sponsors = $all_array['sponsor_id'];
}
$below_details = mysqli_query($con,"SELECT * FROM users WHERE sponsor_id ='$current_user'");
while ($below_array = mysqli_fetch_array($below_details)){
$below_users = $below_array['user_id'];
}
?>
Any kind of help is appreciated. Feel free to ask me the details if there is any confusion in the question.
You can use a recursive CTE to retrieve all the members below a given id -
WITH RECURSIVE pyramid AS (
SELECT u.* FROM users u WHERE sponsor_id = 1 /* starting sponsor_id */
UNION ALL
SELECT u.* FROM pyramid p JOIN users u ON p.id = u.sponsor_id
)
SELECT * FROM pyramid;

What's the correct sql query for this purpose?

I have read in some articles about query's like this:
select *
from `log` as a
where not exists ...
but unfortunately I'm complicated: I know what I want but I can't find the correct query for it.
The all_services table is the Mother table and each user can use 7 services in it. At the beginning, I want to show all 7 services for each user but after that user selected some services and registered those id's in user_services table, I want to show just remaining services like this pic:
please give me the compelete PDO code
http://i.stack.imgur.com/Gdlrl.jpg
Try it:
select a.* from all_services a
join user_services b on a.id = b.service_id
where b.user_id = {user id}
if found it :
$data_obj_se = $db -> prepare("select * from `services` WHERE id NOT IN ( select service_id from `user_services` WHERE user_id='2' ) ");
$data_obj_se -> execute();

MySQL Query, get user_ID then get Restaurant_ID then get restaurantName from 3 tables that match email at user table

I'm new to MySQL and I'm having problem with JOIN. Please give me some hint on how to achieve what I need.
My Table:
"user" table:
- user_id
- user_name
- user_email
"favouriteRestaurant" table:
- favrst_id
- user_id
- rst_id
"restaurant" table:
- rst_id
- rst_name
- rst_city
- rst_cuisine
- rst_phone
- rst_latitude
- rst_longitude
My query process:
Get user_id "WHERE" user_email match provided email address.
Use the user_id to query "favouriteRestaurant", if data available.
Get rst_name of matching rst_id from "favouriteRestaurant" table.
The final data I need is:
favrst_id
rst_id
rst_name
rst_city
rst_cuisine
rst_phone
rst_latitude
rst_longitude
I hope my explanation is clear enough. If it's not clear please ask/comment. Thank you very much.
The following is the actual SQL (above table are simplified) I've tried so far but the result is definitely not what I wanted. It give me all restaurant instead of matching in favRst.
SELECT
user.email,
user.user_id,
favourite_rst.restaurant_id,
favourite_rst.restaurant_id,
favourite_rst.user_id,
restaurant.name
FROM
user,
favourite_rst,
restaurant
WHERE
(user.email = 'user#abc.com')
You can also try this:
SELECT FR.favrst_id, FR.rst_id, R.rst_name, R.rst_city,
R.rst_cuisine, R.rst_phone, R.rst_latitude, R.rst_longitude
FROM user U,
favouriteRestaurant FR,
restaurant R
WHERE U.user_email = "aaaa#example.com"
and U.user_id = FR.user_id
and FR.rst_id = R.rst_id
and compare the execution time using inner join and without using inner join.
Try with this :
SELECT favrst_id, FR.rst_id, rst_name, rst_city,
rst_cuisine, rst_phone, rst_latitude, rst_longitude
FROM user U
INNER JOIN favouriteRestaurant FR ON U.user_id = FR.user_id
INNER JOIN restaurant R ON FR.rst_id = R.rst_id
WHERE user_email = "%$email%"
Hope it helps you
SELECT r.* , fr.favrst_id FROM restaurant r LEFT JOIN favourite_rst fr ON r.rst_id = fr.rst_id LEFT JOIN user u ON fr.user_id = u.user_id WHERE u.user_email = "abc#example.com"

show results of multiple mysql tables and sort

I have 4 tables:
Table 1: Users
id
username
Table 2: Acts
act_id
act
user_id
act_score
act_date
Table 3: Votes
vote_id
act_id
user_voter_id
score_given
date_voted
Table 4: Comments
comment_id
comment
commenter_id
act_commented
date_commented
I want to show the contents of Acts Votes and Comments, based on User ID, combined in a list sorted in date order. Similar idea to Facebook's NewsFeed.
Sample output:
05-02-2014 10:00 Comment: "That's funny"
04-02-2014 12:30 Act Posted: "This is what I did"
04-02-2014 11:00 Comment: "Rubbish"
03-02-2014 21:00 Comment: "Looks green to me"
02-02-2014 09:00 Voted: +10 "Beat my personal best" by Cindy
01-02-2014 14:25 Act Posted: "Finally finished this darn website!"
I have tried to go down the create VIEW route to add all the required info to a table but
it was the wrong path. Now I'm not sure what to do!
Use UNION to combine separate queries. For example, to get the 10 most recent events across the three tables:
(
-- my acts
SELECT a.act_date timestamp,
'Act Posted' type,
a.act description,
u.username
FROM Acts a
JOIN Users u ON u.id = a.user_id
WHERE a.user_id = ?
ORDER BY a.act_date DESC
LIMIT 10
) UNION ALL (
-- votes on my acts
SELECT v.date_voted,
CONCAT('Voted ', v.score_given),
a.act,
u.username
FROM Votes v
JOIN Acts a USING (act_id)
JOIN Users u ON u.id = v.user_voter_id
WHERE a.user_id = ?
ORDER BY v.date_voted DESC
LIMIT 10
) UNION ALL (
-- comments on my acts
SELECT c.date_commented,
'Comment',
c.comment,
u.username
FROM Comments c
JOIN Acts a ON a.act_id = c.act_commented
JOIN Users u ON u.id = c.commenter_id
WHERE a.user_id = ?
ORDER BY c.date_commented DESC
LIMIT 10
)
ORDER BY timestamp DESC
LIMIT 10
first of all make id as a foreign key and use it in rest of the 3 tables while inserting data into those 3 tables.
like for Acts table,table structure should be like below.
Table 2: Acts
id //this is user id which is stored in the session while login.
act_id
act
user_id
act_score
act_date
The another thing to do is manage session for each and every user while he/she logged in.
Store user_id in the session for the further use like below.
session_start();
$_SESSION['user_id']=$_POST['ID'];
Then,fire select query for the particular table.I give you example of select query.
$sql="select * from Acts where id='".$_SESSION['id']."' ORDER BY act_date DESC";
$query=mysql_query($sql) or die("query failed");
Now, you will get result of Acts of particular user order by date.Then print it wherever you want.

MySQL and PHP - Check if user has access to data

I have a crossreference table owner_meeting_crossref with a column (owner_id) for owner IDs and column (meeting_id) for meeting IDs that the owner has access to.
My php script is sent an array of meetings, and I know the current user ID is $current_user_id. How can I efficiently check that the user (owner) has access to the meeting IDs sent in?
One option would be to fetch the meetings from the list that the user has access to, then calculate the difference.
$meetingStr = implode(',', array_map('intval', $meetings));
$accessibleMeetingQuery = $db->prepare("
SELECT meeting_id
FROM owner_meeting_crossref
WHERE owner_id=:uid AND meeting_id IN ($meetingStr)
");
$accessibleMeetingQuery->execute(array(':uid' => $current_user_id));
$accessibleMeetings= $accessibleMeetingQuery->fetchAll(PDO::FETCH_COLUMN);
$inaccessibleMeetings = array_diff($meetings, $accessibleMeetings);
Another would be to do it all from SQL
SELECT m.id
FROM meetings AS m
LEFT JOIN owner_meeting_crossref AS om
ON m.id=om.meeting_id AND om.owner_id=:uid
WHERE m.id IN ($meetingStr)
AND om.meeting_id IS NULL

Categories