mysql join query from 3 tables - php

i want to the join query from three table 1 tbl_customerinfo , 2 tbl_customerinfo ,3- tbl_cust_ext_pref;
i want add to table 3( tbl_cust_ext_pref ) in this query ..
i have using join query from two table and get all informations and code is working a- tbl_customerinfo feild name ( id ,c_shortcode, c_type)
b - tbl_cust_extinfo
feild name ( cx_id ,cx_gender,cs_createdby)
i have use this code
/* code here */
$this->db->select ( this is a table
'tbl_customerinfo.c_id,
tbl_customerinfo.c_shortcode,
tbl_customerinfo.c_type,
/*this is b table tbl_cust_extinfo.cx_id, tbl_cust_extinfo.cx_gender, tbl_cust_extinfo.cs_createdby*/
');
$this->db->from('tbl_customerinfo');
$this->db->join
(
'tbl_cust_extinfo',
'tbl_customerinfo.c_id = tbl_cust_extinfo.cx_id'
);
$query = $this->db->get();
//$info='tbl_customerinfo';
if($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
//print_r($row);
//exit();
$info[] = array(
'c_id' => $row->c_id,
'c_shortcode' => $row->c_shortcode,
'c_type'=> $row->c_type
array(
'cx_id'=> $row-> cx_id,
'cx_gender'=> $row -> cx_gender);

Write your sql query once in a single query:
$sql = 'select * from table1 join table2 on table1.c1 = table2.c2 '
. 'join table3 on table1.c1 = table3.c3';
$res = mysql_query($sql);

Related

how to select multiple rows using mysql and php?

I had two tables
ads
adImages
here table ads id and table adImages adsId are same. here i have to select all the rows from the table ads and adImages, and display it in json format.
My codes looks:
$query="SELECT a.*, b.images FROM `ads` AS a INNER JOIN `adImages` AS b ON a.id = b.adsId";
$result=mysql_query($query);
$value = mysql_num_rows($result);
if($value>=1)
{
while($row = mysql_fetch_array($result))
{
$details[] = array(
'id' => $row['id'],
'location' => $row['location'],
'title'=>$row['title'],
'mobile' => $row['mobile'],
'description' => $row['description'],
'category' => $row['category'],
'images' =>'http://greenwma.com/dev/uploads/'.$row['images'],
);
}
echo json_encode($details);
}
And its output json looks like :
[{"id":"10","location":"9.982852,76.300637","title":"Ggg","mobile":"5555555","description":"Google","category":"BusMedia","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016062319:07:39.jpg{"id":"10","location":"9.982852,76.300637","title":"Ggg","mobile":"5555555","description":"Google","category"BusMedia","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 17:27:05.jpg"},{"id":"11","location":"9.962439,76.305337","title":"Test","mobile":"898566899","description":"Test","category":"Bus Shelters","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:15:16.jpg"},{"id":"11","location":"9.962439,76.305337","title":"Test","mobile":"898566899","description":"Test","category":"Bus Shelters","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:08:50.jpg"},{"id":"11","location":"9.962439,76.305337","title":"Test","mobile":"898566899","description":"Test","category":"Bus Shelters","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:07:39.jpg"}]
here the problem is id,location,title,mobile,description,category are repeating for each image on same adsId.
And my need is that, I have to get json in the format
[{"id":"10","location":"9.982852,76.300637","title":"Ggg","mobile":"5555555","description":"Google ","category":"Bus Media","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:07:39.jpg","http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 17:27:05.jpg"},{"id":"11","location":"9.962439,76.305337","title":"Test","mobile":"898566899","description":"Test","category":"Bus Shelters","images":"http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:15:16.jpg","http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:08:50.jpg","http:\/\/greenwma.com\/dev\/uploads\/MapCapture2016-06-23 19:07:39.jpg"}]
that is, I have to get all images separated by comma in single json object. for that what all changes should I make in the above code.
You can use CONCAT() & GROUP_CONCAT() with sub queries to do it in one query and lesser loops.
SELECT a.*, GROUP_CONCAT(images) images FROM (
SELECT a.*, CONCAT('http://greenwma.com/dev/uploads/', b.images) images
FROM `ads` AS a
INNER JOIN `adImages` AS b ON a.id = b.adsId
) tbl
GROUP BY id

How to get data from multiple columns from 2 tables in sql database?

I have 2 tables name each name shipping_infos and orders. I would like to get multiple columns out of the 2 tables. The 2 tables share one same column which is the user_id column. I have been trying on this code, however it still returns me null. How should i write it?
<?php
include ('classes/functions.php');
if(isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
$check_receipt = "select
shipping_infos.shipping_name,shipping_infos.shipping_address,
shipping_infos.shipping_contact,shipping_infos.shipping_email,
orders.order_date,orders.trx_id,orders.tracking_num from
shipping_infos inner join orders on shipping_infos.user_id = orders.user_id
where user_id= '".$user_id."';";
$run_receipt_checking = mysqli_query($con, $check_receipt);
$result = array();
while($row = mysqli_fetch_array($run_receipt_checking)){
array_push($result,
array(
'shipping_name'=>$row[2],
'shipping_address'=>$row[3],
'shipping_contact'=>$row[4],
'shipping_email'=>$row[5],
'order_date'=>$row[8],
'trx_id'=>$row[1],
'tracking_num'=>$row[2],
));
}
echo json_encode(array("result"=>$result));
} ?>
Try this query:
$check_receipt = "select si.shipping_name,
si.shipping_address,
si.shipping_contact,
si.shipping_email,
o.order_date,
o.trx_id,
o.tracking_num
from shipping_infos si
inner join orders o
on si.user_id = o.user_id
where si.user_id='".$user_id."';";
And change here:
array_push($result,
array(
'shipping_name'=>$row[0],
'shipping_address'=>$row[1],
'shipping_contact'=>$row[2],
'shipping_email'=>$row[3],
'order_date'=>$row[4],
'trx_id'=>$row[5],
'tracking_num'=>$row[6],
));

From PHP how to efficiently execute this search in SQL Server?

I have a database structure something like the following:
Table A: PersonId, GroupId
Table B: GroupId, ParentGroupId
Given a PersonId, I want to find the Ids of all people in parent groups of that person's group.
First I select the ParentGroupId for the given PersonId, by joining with B. Then I do a while loop, selecting and recording the PersonId from A based on the GroupId returned in the previous search, and continue the loop by obtaining the next ParentGroupId from B.
Is this an efficient way to do this search, or is there an option that does not involve a while to "bubble up" in this manner?
(this is a simplified version of the actual scenario, changing the schema is not an option)
$sql = 'SELECT ParentGroupID FROM A WHERE PersonId = ' . $id;
$result = $db->query($sql);
$row = $db->fetch_array($result);
$parent_group = $row['ParentGroupId'];
if(!is_null($parent_group)) {
$parent_ids = array();
while($parent_group > 0) {
//is there a way to do this where I retrieve all managers <= lvl 6 at once, so I don't have to loop in order to 'tier up'?
$sql = 'SELECT ParentGroupID, PersonID
FROM B
INNER JOIN A on ParentGroupID = A.GroupID
WHERE ParentGroupID = ' . $parent_group;
$result = $db->query($sql);
$row = $db->fetch_array($result);
$parent_group = $row['ParentGroupID'];
$parent_ids[] = $row['PersonID'];
}
}
Combining your two queries into one would be more efficient:
$sql = 'SELECT ParentGroupID, PersonID
FROM B
INNER JOIN A on ParentGroupID = A.GroupID
WHERE ParentGroupID IN (
SELECT ParentGroupID FROM A WHERE ParentGroupID > 0
AND PersonId = ' . $id .')' ;

Create a filtered array from two MySQL table

Here's the situation.
I have two table in a DB: tblcustomfieldsvalues (for custom fields entry) and tblclients (contains client list).
tblcustomfieldsvalues has following data structure:
id => 10
relid => 13
data => somedataentry
id => 10
relid => 21
data => someotherdataentry
tblclients has following data structure:
id => 13
firstname => somename
lastname => somelastname
I have this code to create an array of relids which have id = 10:
$sql = mysqli_fetch_array(mysqli_query("SELECT * FROM `tblcustomfieldsvalues` WHERE `id` = '10'"));
$cids = array();
while ($row = $sql)
{
array_push($cids, $row['relid']);
}
Now that I have user IDs of those who have filled their custom fields with some data in the $cids array, how can I get those users details from tblclients?
Thanks in advance.
Sounds like you just need to use an INNER JOIN:
SELECT t2.*
FROM tblcustomfieldsvalues t
INNER JOIN tblclients t2 ON t.relid = t2.id
WHERE t.ID = 10
Good luck!
$sql = mysqli_fetch_array(mysqli_query("SELECT * FROM `tblcustomfieldsvalues` WHERE `id` = '10'"));
$cids = array();
while ($row = $sql)
{
//array_push($cids, $row['relid']);
$sql1 = mysqli_fetch_array(mysqli_query("SELECT * FROM `tblclients ` WHERE `id` = '$row['relid']'"));
while ($row1 = $sql1)
{
//echo your output
}
}
OR
SELECT * FROM
tblcustomfieldsvalues cv,tblclients c WHERE
cv.id = 10 and cv.id = c.id
Without knowing the table structure of tblclients I can't be sure, but it sounds like instead of doing separate queries and looping you could just use a join:
SELECT
*
FROM
tblcustomfieldsvalues
NATURAL JOIN tblclients
WHERE
id = 10

Combine mysql query with sub query results into one PHP array

I have a table that contains events, to list these events I loop through the event table, check the event type and look up it's value in it's specific table with it's eventId.
At the moment this uses one query to get the 20 events and then up to 3 queries to get the data on those events. I currently have it coded procedurally but need to change it so that at the end it just returns the data in array form.
Here's a Pseduo code example of what I need to achieve:
while(eventQuery):
if commentQueryResult;
$array .= commentQueryResult;
if forumPostQueryResult;
$array .= forumPostQueryResult;
if uploadItemQueryResult;
$array .= uploadItemQueryResult;
endwhile;
return $array; // Combined returned results as one array
I will then be able to access the data and just foreach loop through it.
I'm just not sure the best way to combine multiple result sets into an array?
OR you could try and combine them into one query ...
$eventResult = mysql_query(
'SELECT userevent.event, userevent.eventId, userevent.friendId
FROM userevent
WHERE userevent.userId = 1 OR userevent.friendId = 1
ORDER BY userevent.id DESC
LIMIT 20'
);
while ($eventRow = mysql_fetch_row($eventResult)){
if($eventRow[0] == 1){
$result = mysql_fetch_array(mysql_query("
SELECT forumRooms.id, forumRooms.title
FROM forumPosts
INNER JOIN forumRooms ON forumPosts.`forumTopic` = forumRooms.`id`
WHERE forumPosts.id = '$eventRow[1]'"));
}
elseif($eventRow[0] == 2){
$result = mysql_fetch_array(mysql_query("
SELECT game.id, game.uriTitle, game.title
FROM usergamecomment
INNER JOIN game ON usergamecomment.`gameId` = game.id
WHERE usergamecomment.id = $eventRow[1]"));
}
elseif($eventRow[0] == 4){
$result = mysql_fetch_array(mysql_query("
SELECT usercomment.comment, UNIX_TIMESTAMP(usercomment.TIME), `user`.id, `user`.username, `user`.activate
FROM usercomment
INNER JOIN `user` ON usercomment.`userId` = `user`.id
WHERE usercomment.id = $eventRow[1]
AND `user`.activate = 1"));
}
elseif($eventRow[0] == 5){
$result = mysql_fetch_array(mysql_query("
SELECT game.id, game.title, game.uriTitle
FROM game
WHERE game.id = $eventRow[1]"));
}
// Combined Results as array
}
I'm in the process of converting all of these to PDO, that's the next step after working out the best way to minimise this.
Challenge accepted. ;)
Since you are actually only interested in the results inside the while loop, you could try this single query. Due to the LEFT JOINS it might not be faster, pretty much depends on your database. The final $result contains all elements with their respective fields.
$result = array();
$q = 'SELECT userevent.event AS userevent_event,
userevent.eventId AS userevent_eventId,
userevent.friendId AS userevent_friendId,
forumRooms.id AS forumRooms_id,
forumRooms.title AS forumRooms_title,
game.id AS game_id,
game.uriTitle AS game_uriTitle,
game.title AS game_title,
usercomment.comment AS usercomment_comment,
UNIX_TIMESTAMP(usercomment.TIME) AS usercomment_time,
user.id AS user_id,
user.username AS user_username,
user.activate AS user_activate,
g2.id AS game2_id,
g2.uriTitle AS game2_uriTitle,
g2.title AS game2_title
FROM userevent
LEFT JOIN forumPosts ON forumPosts.id = userevent.eventId
LEFT JOIN forumRooms ON forumPosts.forumTopic = forumRooms.id
LEFT JOIN usergamecomment ON usergamecomment.id = userevent.eventId
LEFT JOIN game ON usergamecomment.gameId = game.id
LEFT JOIN usercomment ON usercomment.id = userevent.eventId
LEFT JOIN user ON usercomment.userId = user.id
LEFT JOIN game g2 ON userevent.eventId = g2.id
WHERE (userevent.userId = 1 OR userevent.friendId = 1)
AND userevent.eventId >= (SELECT userevent.eventId
WHERE userevent.userId = 1 OR userevent.friendId = 1
ORDER BY userevent.id DESC LIMIT 1,20);';
$r = mysql_query($q);
while ( $o = mysql_fetch_row($r) ) {
switch($o['userevent_event']) {
case 1:
$result[] = array(
'id' => $o['forumsRooms_id'],
'title' => $o['forumsRooms_title'],
);
break;
case 2:
$result[] = array(
'id' => $o['game_id'],
'uriTitle' => $o['game_uriTitle'],
'title' => $o['game_title'],
);
break;
case 4:
$result[] = array(
'comment' => $o['usercomment_comment'],
'time' => $o['usercomment_time'],
'id' => $o['user_id'],
'username' => $o['user_username'],
'activate' => $o['user_activate'],
);
break;
case 5:
$result[] = array(
'id' => $o['game2_id'],
'uriTitle' => $o['game2_uriTitle'],
'title' => $o['game2_title'],
);
break;
}
}
Note: Eventually, the query has to be edited slightly, I just wrote that out of my head w/o testing. Optimization can surely be done if I'd knew more about the db structure.
Also, this is merely a proof of concept that it can indeed be done with a single query. ;)

Categories