How to collect data from two related tables - php

I am trying to get data from 2 different tables: users and comments.
I want to return comment data and user data depending on the commentsenderid .
<?php
$commentpostid = $_POST['commentpostid'];
$sql = "SELECT * FROM comments where commentpostid = '{$commentpostid}'";
$sqll = mysqli_query($db, $sql); // $db->query() is also accepted.
$result = mysqli_fetch_all($sqll, MYSQLI_ASSOC);
echo json_encode($result);
Result:
[
{
"commentid": "93",
"comment": "naber kankam Benin",
"commentpostid": "1006",
"commentsenderid": "12"
},
{
"commentid": "95",
"comment": "kankam selam!",
"commentpostid": "1006",
"commentsenderid": "3135"
}
]
Should be:
[
{
"commentid": "93",
"comment": "naber kankam Benin",
"commentpostid": "1006",
"commentsenderid": "12",
"username": "denemeuser",
"userbolum": "denemebolum",
"useryas": "useryasdeneme"
},
{
"commentid": "95",
"comment": "kankam selam!",
"commentpostid": "1006",
"commentsenderid": "3135",
"username": "denemeuser",
"userbolum": "denemebolum",
"useryas": "useryasdeneme"
}
]
[]
[]

You select all comments, join them with users whose id matches the id of the authors of comments, you select only those whose post matches the value you are looking for.
SELECT c.*, u.username, u.userbolum, u.useryas
FROM comments c
JOIN users u ON c.commentsenderid = u.userid
WHERE commentpostid = ?

Related

MYSQL - Combine 2 tables in one query BUT have 2 WHERE/IN clauses

I am looking to do one MYSQL query on 2 tables and get the results as one object/array. My problem is that the query needs to matcha set of IDs that are named differently in both tables.
Let's say I have a urls table and a products table and they both have a column that corresponds to the ID I'm searching for but named differently... in the urls table its called resource_id, and in the products table its called productid.
URLS TABLE:
id | resource_id | url
PRODUCTS TABLE:
productid | title | description | thumbnail
So in php I have a list of IDs that use to retrieve both tables combined BUT only where the urls.resource_id and products.productid equal those IDs.
Here is what i have so far:
$ids = ["18552", "18554", "18555", "18556"];
$newIds = implode(",",$ids);
$q3 = " SELECT products.title as title, urls.url as url
FROM urls, products
WHERE urls.resource_id IN ($newIds)
AND products.productid IN ($newIds)";
At the moment this returns the 4 results based on the $ids variable 4 times - 16 results in total. I think it has to do with the WHERE urls.resource_id IN ($newIds) AND products.productid IN ($newIds portion of the query since 4 * 4 = 16, but I could be wrong.
Something like this:
{ "title": "Prod 1", "url": "prod-one.html" },
{ "title": "Prod 2", "url": "prod-two.html" },
{ "title": "Prod 3", "url": "prod-three.html" },
{ "title": "Prod 4", "url": "prod-four.html" },
{ "title": "Prod 1", "url": "prod-one.html" },
{ "title": "Prod 2", "url": "prod-two.html" },
{ "title": "Prod 3", "url": "prod-three.html" },
{ "title": "Prod 4", "url": "prod-four.html" },
{ "title": "Prod 1", "url": "prod-one.html" },
{ "title": "Prod 2", "url": "prod-two.html" },
{ "title": "Prod 3", "url": "prod-three.html" },
{ "title": "Prod 4", "url": "prod-four.html" },
{ "title": "Prod 1", "url": "prod-one.html" },
{ "title": "Prod 2", "url": "prod-two.html" },
{ "title": "Prod 3", "url": "prod-three.html" },
{ "title": "Prod 4", "url": "prod-four.html" },
Not really sure how to achieve this without the repeats... any suggestions?
ALSO - this database is from a shopping cart system so I tried to simplify the example as much as possible without losing clarity in my question/example.
Thank you in advance!
Please try this query. It shows all the entrys that exist in both tables and a in $tdis
$ids = ["18552", "18554", "18555", "18556"];
$newIds = implode(",",$ids);
$q3 = " SELECT p.title as title, u.url as url
FROM urls u INNER JOIN products p ON u. resource_id = p.productid
WHERE u.resource_id IN ($newIds);";

Select inside a select query MYSQL

Hello! I have a query that needs to output screens data.
Each screens has 4 booths to be shown. I need a query with one result (because I just have one screen) And has 4 booths in it (coz I assigned 4 booths)
Here's my query:
$result = DB::select("
SELECT
`A`.`scr_name`,
`A`.`mission_id`,
`B`.`booth_id`,
`E`.`name`
FROM `tbl_screen` `A`
LEFT JOIN
`tbl_screen_booths` `B`
ON `B`.`screen_id` = `A`.`id`
LEFT JOIN
`tbl_service_booths` `C`
ON `B`.`booth_id` = `C`.`id`
LEFT JOIN
`tbl_missions_services` `D`
ON `C`.`mission_services_id` = `D`.`id`
LEFT JOIN
`tbl_services` `E`
ON `D`.`service_id` = `E`.`id`
WHERE `A`.`mission_id` = $mission_id
GROUP BY
`B`.`booth_id`;
");
return $result;
I want something like this:
"scr_name": "Test Screen",
"mission_id": 2,
"name": "booth1", //index[0]
"name": "booth2", //index[1]
"name": "booth3", //index[2]
"name": "booth4" //index[4]
My query returns something like this:
[
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 7,
"name": "booth1"
},
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 9,
"name": "booth2"
},
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 10,
"name": "booth3"
},
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 11,
"name": "booth4"
}
]
the result is okay.. just need a little iterate to get the value..
$data['scr_name'] = $result[0]->scr_name;
$data['mission_id'] = $result[0]-> mission_id;
foreach($result as $index => $item) {
$data['name'.($index+1)] => $item->name;
}
result:
"scr_name": "Test Screen",
"mission_id": 2,
"name1": "booth1", //index[0]
"name2": "booth2", //index[1]
"name3": "booth3", //index[2]
"name4": "booth4" //index[4]
array key cant have same key name

Merge 2 different tables without repeating values PHP

I have 2 tables; the first one is user_in_event table
which here role can be regular, waiting for ack or moderator
and the second one is user table
Here the role can be regular or admin
I want to take the role from user_in_event table, based on the event_id and output all users info (beside user role) and output in a single JSON
I have tried to use LEFT JOIN
$query = "SELECT user_in_event.role, user_in_event.user_id, user.name, user.email, user.birthday, user.phone_number, user.address, user.image
FROM user LEFT JOIN user_in_event
ON user_in_event.event_id = '".$event_id."'
LIMIT $num_of_rows";
$result = mysqli_query($con,$query)
or die(mysqli_error($con));
// print_r($query);
while ($row = mysqli_fetch_assoc($result)) {
$response[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($response);
but I got messed up data
[
{
"role": "moderator",
"user_id": "2",
"name": "ofir",
"email": "ofir#ofr.com",
"birthday": "08/12/2016",
"phone_number": "123",
"address": "yoqneam",
"image": "http://imgur.com/a/KslOW"
},
{
"role": "waiting for ack",
"user_id": "21",
"name": "ofir",
"email": "ofir#ofr.com",
"birthday": "08/12/2016",
"phone_number": "123",
"address": "yoqneam",
"image": "http://imgur.com/a/KslOW"
}
]
PS: I also tried to make 2 different queries and combine the JSON and user array_merge_recursive but I got 2 subs arrays instead of a single one
Please try :
SELECT user_in_event.role, user_in_event.user_id, user.name, user.email
FROM user
LEFT JOIN user_in_event ON user_in_event.user_id = user.user_id
WHERE user_in_event.event_id =25
LIMIT 0 , 30
Here event_id is static. run this query to your database and let me know.

Get JSON from OneToOne relation using propel

I'm going to get a JSON like following structure from my database:
{
"Users": [
{
"Id": 1,
"Name": "a",
"Family": "b",
"RegisterId": 1,
"AccessType": 1,
"Username": "abc"
},
{
"Id": 2,
"Name": "x",
"Family": "y",
"RegisterId": 2,
"AccessType": 1,
"Username": "xyz"
}
]
}
Id,Name,Family,RegisterId,AccessType are User_TBL columns and Username is Register_TBL column.
I can get this JSON using below query:
SELECT u.id,u.name,u.family,u.access_type,u.register_id,r.username
FROM `user` as u LEFT JOIN `register` as r
ON u.register_id = r.id
I'm trying to use below line using propel, but it just shows all User_TBL columns.
$userList = UserQuery::create()-> joinWith('User.Register')-> find();
What's your suggestion ?!
I used below code and it solved my problem.
$userList = UserQuery::create()
-> leftJoinRegister()
-> select(array('ID','NAME','FAMILY','AccessType'))
-> withColumn('Register.Username' , 'Username')
->find();

fql.multiquery returning empty array

I'm am trying to query all the photo albums of a page and get each albums cover photo. Below is the code I have that returns an empty result.
I am able to make both the queries separately without the problem, so it is not a permissions issue.
$album_fql = "SELECT aid, owner, name, object_id, cover_pid, cover_object_id
FROM album
WHERE owner = 'xxxxxxx'";
$albumpic_fql = "SELECT pid, src_small
FROM photo
WHERE pid IN (SELECT cover_pid FROM #query1)";
$album_param = array(
'method' => 'fql.multiquery',
'queries' => '{"query1":"' . $album_fql . '", "query2":"' . $albumpic_fql . '"}');
$album_fqlResult = $facebook->api($album_param);
print_r($album_fqlResult);
Any ideas?
you can do that in a nested query rather than as a multi query.
SELECT pid, src_small
FROM photo
WHERE pid in (SELECT cover_pid FROM album where owner={page id here})
for example here's the list of album covers I got from CocaCola's Facebook page
SELECT pid, src_small
FROM photo
WHERE pid in (SELECT cover_pid FROM album where owner=40796308305)
LIMIT 5
returned:
{
"data": [
{
"pid": "40796308305_2143765",
"object_id": 110516463305,
"src_small": "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-snc1/6570_110516463305_40796308305_2143765_6253354_t.jpg"
},
{
"pid": "40796308305_8753877",
"object_id": "10150500888203306",
"src_small": "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/398389_10150500888203306_40796308305_8753877_1814220329_t.jpg"
},
{
"pid": "40796308305_8751674",
"object_id": "10150500434253306",
"src_small": "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/407475_10150500434253306_40796308305_8751674_1040781388_t.jpg"
},
{
"pid": "40796308305_8742570",
"object_id": "10150498588158306",
"src_small": "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/396541_10150498588158306_40796308305_8742570_1378170213_t.jpg"
},
{
"pid": "40796308305_8742259",
"object_id": "10150498546173306",
"src_small": "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-snc7/402667_10150498546173306_40796308305_8742259_287537096_t.jpg"
}
]
}
If you want to try your multiquery, then try to name the queries starting at index 0 instead of 1. e.g. query0 and query1 This is the only way the C# SDK allows it, maybe the php SDK requires that too.
Finally figured it out. I had to merge the queries into 1 variable and escape the single quotes.
$queries = '{
"query1" : "SELECT aid, name, cover_pid FROM album WHERE owner = \'xxxxxxxxxxx\'",
"query2" : "SELECT aid, images FROM photo WHERE pid IN (SELECT cover_pid FROM #query1)"
}';

Categories