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
Related
I want to convert LARGE NUMBER of MySQL data to JSON using PHP. I have 20K and above records but I am unable to convert MySQL data to JSON. I want to create REST API so need to send(response) data in JSON format.
I have tried this but not getting output:
Code:
$query = mysql_query("SELECT table1.field1, table1,field2, table1.field3, table2.field4 FROM table1 LEFT JOIN table2 ON table1.field1 = table2.field1");
$result = array();
while($row = mysql_fetch_assoc($query))
{
$result[] = array('Name' => $row["field1"], 'Last Name' => $row['field2'], 'country' => $row["field3"], 'location' => $row["field4"]);
}
echo json_encode($result);
Asides from the error with your query which I'm assuming is just a typing error in your question because no one labels their columns as field1, field2 etc.
The issue you are facing is more than likely an encoding issue. Try the following which encodes the result as UTF8 and will hopefully result in valid JSON.
mysql_set_charset ("UTF8");
$query = mysql_query("SELECT table1.field1, table1field2, table1.field3, table2.field4 FROM table1 LEFT JOIN table2 ON table1.field1 = table2.field1");
$result = array();
while($row = mysql_fetch_assoc($query))
{
$result[] = array('Name' => $row["field1"], 'Last Name' => $row['field2'], 'country' => $row["field3"], 'location' => $row["field4"]);
}
echo json_encode($result);
Your query is wrong. change it to
SELECT table1.field1, table1.field2, table1.field3, table2.field4 FROM table1 LEFT JOIN table2 ON table1.field1 = table2.field1
need table1.field2 instead of table1,field2
you have mysql query syntax error. Intead of table1,field2 use table1.field2
I need to fetch data from DB in an array using PHP and MySQL. In my case I am having 1 set of data in the given condition but the same set of data is coming multiple times. I am providing my code below.
$pro_id=$_GET['pro_id'];
$userid=$_GET['user_id'];
$sql="
SELECT s.id,
s.voucher_code,
s.merchant,
s.date,
s.receiver,
s.sender,
s.serial_no,
s.image,
s.expired_date,
s.product_id,
c.status,
c.redeem_status,
sup.supplier_id,
sup.NAME,
a.NAME AS sender_name,
v.discount,
v.discount_type,
v.voucher_amount,
p.product_name AS pro_name
FROM db_send_evoucher_code s
INNER JOIN db_code c
ON s.voucher_code = c.total_voucher_code
INNER JOIN db_supplier sup
ON s.merchant = sup.supplier_id
INNER JOIN medilink_admin a
ON s.sender = a.admin_id
INNER JOIN db_voucher_code v
ON c.voucher_code_id = v.voucher_code_id
INNER JOIN db_product_info p
ON s.product_id = p.pro_id
WHERE s.receiver = '". $userid ."'
and s.product_id = '". $pro_id ."'";
$sqlqry = mysqli_query($con, $sql);
if (mysqli_num_rows($sqlqry) > 0) {
while ($row = mysqli_fetch_array($sqlqry)) {
if ($row['discount_type'] == 'Flat') {
$distype = 1;
}
if ($row['discount_type'] == 'percentage') {
$distype = 2;
}
$data['data'][] = $data['data'][] = array("voucher_code" => $row['voucher_code'], "send_by" => $row['sender_name'], "image" => $row['image'], "expired_date" => $row['expired_date'], "supplier_name" => $row['name'], "sending_date" => $row['date'], "supplier_id" => $row['supplier_id'], "discount" => $row['discount'], "product_id" => $row['product_id'], "product_name" => $row['pro_name'], "redeem_status" => $row['redeem_status'], "voucher_amount" => $row['voucher_amount'], "discount_type" => $distype, "imagepath" => $imagepath);
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
} else {
$data['data'] = array();
echo json_encode($data);
}
Here in the given condition I have one set of data inside DB but it's coming two times. Here is my output:
{"data":[{"voucher_code":"FIFLTBH8567","send_by":"Medilink","image":"glotnzgrqbyb9_97yw155165stt9_eneoji_l.jpg","expired_date":"22-02-2016","supplier_name":"Eneoji","sending_date":"2016-02-18 16:11:35","supplier_id":"9","discount":"20","product_id":"52","product_name":"Eneoji Fomentation Therapy","redeem_status":"0","voucher_amount":"2000","discount_type":2,"imagepath":"http://li120-173.members.linode.com/crm_beta/upload/"},{"voucher_code":"FIFLTBH8567","send_by":"Medilink","image":"glotnzgrqbyb9_97yw155165stt9_eneoji_l.jpg","expired_date":"22-02-2016","supplier_name":"Eneoji","sending_date":"2016-02-18 16:11:35","supplier_id":"9","discount":"20","product_id":"52","product_name":"Eneoji Fomentation Therapy","redeem_status":"0","voucher_amount":"2000","discount_type":2,"imagepath":"http://li120-173.members.linode.com/crm_beta/upload/"}]}
You should check if there is 2 lines with the same foreign key value in one of the inner joined table.
For ex,if you have 2 rows with total_voucher_code = "FIFLTBH8567" in table db_code, even if the reste of the row is different, you'll get this kind of unexpected result.
Try to write your SELECT statement as below
SELECT DISTINCT s.id,s.voucher_code,s.merchant etc...
Use distinct in your sql, so you don't get any duplicates rows:
$sql="select distinct s.id,s.voucher_code,s.merchant,s.date,s.receiver,s.sender,s.serial_no,s.image,s.expired_date,s.product_id,c.status,c.redeem_status,sup.supplier_id,sup.name,a.name AS sender_name,v.discount,v.discount_type,v.voucher_amount,p.Product_name AS pro_name
from db_send_evoucher_code s
INNER JOIN db_code c ON s.voucher_code=c.total_voucher_code
INNER JOIN db_supplier sup ON s.merchant=sup.supplier_id
INNER JOIN medilink_admin a ON s.sender=a.admin_id
INNER JOIN db_voucher_code v ON c.voucher_code_id=v.voucher_code_id
INNER JOIN db_product_info p ON s.product_id=p.pro_Id
where s.receiver='".$userid ."' and s.product_id='".$pro_id."'";
I am new to php. I can't figure out how to query my db to list this mockup. For each array, I want to query the db to list only what is related to the left in ''.
My db consist of 2 tables.
table1 = album
id, name
table2 = picture
id, album, picPath
$q_albums = array(
'People' => array(
ALBUM_PATH.'4.jpg',
ALBUM_PATH.'11.jpg',
ALBUM_PATH.'10.jpg'),
'Nature' => array(
ALBUM_PATH.'2.jpg',
ALBUM_PATH.'3.jpg',
ALBUM_PATH.'5.jpg',
ALBUM_PATH.'6.jpg',
ALBUM_PATH.'7.jpg'),
'Art' => array(
ALBUM_PATH.'1.jpg',
ALBUM_PATH.'8.jpg',
ALBUM_PATH.'9.jpg',
ALBUM_PATH.'2.jpg'),
'Wilderness' => array(
ALBUM_PATH.'3.jpg',
ALBUM_PATH.'2.jpg',
ALBUM_PATH.'5.jpg',
ALBUM_PATH.'7.jpg',
ALBUM_PATH.'6.jpg'),
'Photography' => array(
ALBUM_PATH.'8.jpg',
ALBUM_PATH.'1.jpg',
ALBUM_PATH.'9.jpg',
ALBUM_PATH.'12.jpg'),
'Fashion' => array(
ALBUM_PATH.'11.jpg',
ALBUM_PATH.'4.jpg',
ALBUM_PATH.'10.jpg'),
);
As dev-null-dweller notes, you need to build the array from the query results in a loop. Fortunately, it's pretty easy:
$sql = <<<END
SELECT album.name AS albumName, picture.picPath AS picPath
FROM album JOIN picture ON album.id = picture.album
END;
$res = $mysqli->query( $sql );
$q_albums = array();
while ( $row = $res->fetch_object() ) {
// this line actually build the array, entry by entry:
$q_albums[ $row->albumName ][] = $row->picPath;
}
$res->close();
Edit: As Mr. Radical notes, if you want your results to include empty albums, you should change the JOIN to a LEFT JOIN. If you do that, the query will return a row with a null picPath for any empty albums, so you'll have to deal with those null paths somehow. One way would be to include something like the following code after building the array:
foreach ( $q_albums as $album => &$pics ) {
// remove dummy null entries from empty albums
if ( !isset( $pics[0] ) ) array_shift( $pics );
}
#Ilmari Karonen I would use LEFT JOIN instead of JOIN.
SELECT album.name AS albumName, picture.picPath AS picPath
FROM album LEFT JOIN picture ON album.id = picture.album
I am trying to make a page with a list of posts, and underneath each post all the comments belonging to that post. Initially I wanted to use just one query to retrieve all the posts + comments using the SQL's JOIN, but I find it impossible to for example retrieve a post with multiple comments. It only displays the posts with a maximum of 1 comment per post, or it just show a post multiple times depending on the amount of comments.
In this related question, somebody talked about using 2 queries:
How to print posts and comments with only one sql query
But how do I do this?
I've got the query and a while loop for posts, but I obviously don't want to run a query for comments for each post inside that loop.
$getPost = mysql_query('SELECT p.post_id,
p.user_id,
p.username,
p.content
FROM post p
ORDER BY p.post_id DESC');
while($row = mysql_fetch_array($getPost))
{
...
}
Table structure (reply is the table for storing comments):
POST (post_id (primary key), user_id, username, content, timestamp)
REPLY (reply_id (primary key), post_id, username, reply_content, timestamp)
You can do it in a single query, which is OK if the amount of data in your original posts is small:
$getPost = mysql_query('SELECT
p.*,
r.reply_id, r.username r_username, r.reply_content, r.timestamp r_timestamp
FROM post p
left join reply r
ORDER BY p.post_id DESC'
);
$posts = array();
$last_id = 0;
while($row = mysql_fetch_array($getPost))
{
if ($last_id != $row['post_id']) {
$posts[] = array(
'post_id' => $row['post_id'],
'user_id' => $row['user_id'],
'username' => $row['username'],
'content' => $row['content'],
'timestamp' => $row['timestamp'],
'comments' => array()
);
}
$posts[sizeof($posts) - 1]['comments'][] = array(
'reply_id' => $row['reply_id'],
'username' => $row['r_username'],
'reply_content' => $row['reply_content'],
'timestamp' = $row['r_timestamp']
);
}
Otherwise, break it into two queries like so:
$getPost = mysql_query('SELECT
p.*,
FROM post p
ORDER BY p.post_id DESC'
);
$rows = array();
$ids = array();
$index = array();
while($row = mysql_fetch_assoc($getPost)) {
$row['comments'] = array();
$rows[] = $row;
$ids[] = $row['post_id'];
$index[$row['post_id']] = sizeof($rows) - 1;
}
$getComments = mysql_query('select r.* from replies r where r.post_id in ("'
. join('","', $ids)
. '")');
while ($row = mysq_fetch_assoc($getComments)) {
$rows[$index[$row['post_id']]]['comments'][] = $row;
}
... Or something like that. Either option allows you to litter your first query with WHERE clauses and so forth to your heart's content. The advantage of the 2nd approach is that you don't re-transmit your original post data for each comment!
In order to also get those posts without comments, you need to use a LEFT OUTER JOIN. In that case, any row in the first table without any corresponding rows in the second table will be paired with a row consisting of null values.
SELECT * FROM posts
LEFT OUTER JOIN comments ON posts~post_id = comments~post_id;
By the way: there is also a RIGHT OUTER JOIN. When you would use that, you would get all comments, including those where the parent post got lost somehow, but no posts without comments.
table 1 = events -> holds a list of events
table 2 = response -> holds a list of users responses has a foreign key of eid which corresponds with events table
I need to join the tables together so it can return an array similar to this on php.
array(
0 => array(
'title' =>'', //title of events table
'contents' =>'this is a demo', //contents of events table
'users' => array( //users comes from response table
0 = array(
'firstname'=>'John',
),
1 = array(
'firstname'=>'James',
)
)
)
);
can this be done? using mysql only? coz i know you can do it on php.
You can gather all the necessary data in MySQL with a single JOIN query.
However, PHP will not return an array like your example by default. You would have to loop over the query result set and create such an array yourself.
I'm pretty sure the answer is no, since mysql always returns a "flat" resultset. So, you can get all the results you're looking for using:
SELECT e.title, e.contents, r.firstname
FROM events e LEFT JOIN response r ON e.id = r.eid
ORDER BY e.id, r.id
And then massaging it into the array with php, but I imagine this is what you're doing already.
EDIT:
By the way, if you want 1 row for each event, you could use GROUP_CONCAT:
SELECT e.title, e.contents, GROUP_CONCAT(DISTINCT r.firstname ORDER BY r.firstname SEPARATOR ',') as users
FROM events e LEFT JOIN response r ON e.id = r.eid
GROUP BY e.id
Just as Jason McCreary said. For you convenience, here is the query you need (though the field names might not be matching your db structure, as you did not provide this information)
SELECT
*
FROM
events
LEFT JOIN
responses ON (events.id = responses.eid)
The SQL is:
SELECT events.id, events.title, events.contents,
response.id AS rid, response.firstname
FROM events LEFT JOIN response
ON events.id = response.eid
I thought I would show you how to massage the results in to the array as you wished:
$query = "SELECT events.id, events.title, events.contents, response.id AS rid, response.firstname
FROM events LEFT JOIN response ON events.id = response.eid";
$result = mysql_query($query);
$events = array();
while ($record = mysql_fetch_assoc($result)) {
if (!array_key_exists($record['id'], $events)) {
$events[$record['id']] = array('title' => $record['title'], 'contents' => $record['contents'], 'users' => array());
}
if ($record['rid'] !== NULL) {
$events[$record['id']]['users'][$record['rid']] = array('firstname' => $record['firstname']);
}
}
mysql_free_result($result);