Select inside a select query MYSQL - php

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

Related

How to collect data from two related tables

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 = ?

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);";

how to make array of array by looping result from a query

I have a survey about games, and I have one table for the games data, and another for people's answers.
I want to output an array in Json format for answers with each of the 3 favorite games name and their year in an array of array.
expected output
[
{
"id": "1",
"username": "userX",
"g1": {"name": "game1", "year": "1991"},
"g2": {"name": "game2", "year": "1992"},
"g3": {"name": "game3", "year": "1993"},
}
]
what i've tried
$sql = "SELECT * FROM tbAnswers AS answer INNER JOIN tbgames AS game ON answer.g1 = game.id";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->execute();
$answer = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if(empty($answer)) {
$response->getBody()->write
('
{
"error":
{
"status":"400",
"message":"Invalid Request"
}
}');
} else {
$response->getBody()->write(json_encode($answer));
}
} catch(PDOException $e) {
$response->getBody()->write
('
{
"error":
{
"message":'. $e->getMessage() .'
}
}');
}
the current output
[
{
"id": "1",
"username": "userX",
"name": "game1",
"year": "1991"
}
]
I think i should do a foreach somewhere in else to go through each game and echo the result of it based on the id from answers, but i am not sure how to apply it
where to place to foreach
how to select and get the results based on each game id
how to do it in json format
i'm sure it's not how i am doing it, this is how i am trying to echo the data in else
echo"[";
echo"\n{";
echo"\n";
echo '"id:"'.' "'.$answer[0]->id.'",';
echo"\n";
echo"}\n";
echo"]";
here are my tables structure
tbGames
id , name , year
1 , 'game1' , '1991'
2 , 'game2' , '1992'
3 , 'game3' , '1993'
4 , 'game4' , '1994'
tbAnswers
id , name , g1 , g2 , g3
1 , userX , 1 , 2 , 3
2 , userY , 3 , 1 , 4
3 , userZ , 1 , 1 , 2
4 , userW , 2 , 3 , 4
Using this query:
$sql = "SELECT answer.id a_id, answer.name a_name, game1.id g1_id, game1.name g1_name, game1.year g1_year, game2.id g2_id, game2.name g2_name, game2.year g2_year, game3.id g3_id, game3.name g3_name, game3.year g3_year FROM tbAnswers AS answer INNER JOIN tbgames AS game1 ON answer.g1 = game1.id INNER JOIN tbgames AS game2 ON answer.g2 = game2.id INNER JOIN tbgames AS game3 ON answer.g3 = game3.id";
you should change your else statement content to:
} else {
foreach($answer as $value) {
$array_resp[]=[
'id' => $value->a_id,
'username' => $value->a_name,
'g1' => ['name'=>$value->g1_name, 'year'=>$value->g1_year],
'g2' => ['name'=>$value->g2_name, 'year'=>$value->g2_year],
'g3' => ['name'=>$value->g3_name, 'year'=>$value->g3_year],
];
}
$response->getBody()->write(json_encode($array_resp));
}

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();

Categories