简体   繁体   中英

mysql: get data from two tables depends on id of the first table and the result in json

I've 2 tables, I want to get data from the first one depends on "id", and the data from second one depends on the "gid" that same as "id" from the first table, in JSON.

Example:

First Table: 
- - - - - - -
id  name
1   Aaron
2   Caleb
3   Albert
4   Ethan

Second Table:
- - - - - - -
id  gid image
1   1   http://.......image1.jpg
2   1   http://.......image2.jpg
3   2   http://.......image3.jpg
4   3   http://.......image4.jpg
5   3   http://.......image5.jpg
6   3   http://.......image6.jpg

I want the result when I request id=1, Something like this:

"names": [
    {

     "id": 1,

     "name": "Aaron"
          "images":[
             {
                "id" :1
                "url":http://.......image1.jpg
             },
             {
                "id" :2
                "url":http://.......image2.jpg
             }
       ]
   }
]

This some of my code:

$SqlInfo = "Select * from tabel1 where id='$id'";

$obj = json_decode($_GET["x"], false);
$stmt = $con->prepare($SqlInfo);
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode(array(
    'status' => 'Ok',
    'name' => $outp
    ));

to be more specific, my above code , bring json format for the first table, I want to insert the result of the second table in the same result of json (of the first table). Thank you ...

First, you need the result of first table to decode into Array.

$first_table = array(
    '0'=> ['id'=> 1, 'name' =>'Aaron' ],
    '1'=> ['id'=> 2, 'name' =>'Caleb' ],
    '2'=> ['id'=> 3, 'name' =>'Albert'],
    '3'=> ['id'=> 4, 'name' =>'Ethan' ]
    );

//create function to retrieve images by ID from Second Table 
function get_images($id)
{
$SqlInfo = "Select id, image as url from tabel2 where gid='$id'";
$stmt = $con->prepare($SqlInfo);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);

    return $outp;
}   

// create a new object
$new_array=array();

//Loop first table
foreach ( $first_table as $key => $value){

$new_array[$value['name']]  = [
                                'name' => $value['name'],
                                'id' => $value['id'],
                                'images' => get_images($value['id']) // Get images from function
                               ];

}

$final = json_encode($new_array);

This was not tested, but solution should be in this direction

first you can use inner join to combine result from both table

$sql = "select 
           t2.gid,
           t2.id,
           t2.image,
           ti.name 
        from 
            second_table as t2
        join first_table as t1 on t2.gid = t1.id 
        where id='$id'           
       ";

$obj = json_decode($_GET["x"], false);
$stmt = $con->prepare($SqlInfo);
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(PDO::FETCH_ASSOC);
/*PDO::FETCH_ASSOC return result in associative array */
$arr = array();
if(!empty($outp)){

    $i =1;/* this is used so that first table data can only be feed to array once*/

    foreach($outp as $val){
        if($i ==1){
            $arr['id'] = $val['gid'];
            $arr['name'] = $val['name'];
        }
        $tmp = array();
        $tmp['id'] = $val['gid'];
        $tmp['url'] = $val['image'];
        $arr['images'][] = $tmp;
        $i++;
        /*increment $i so that we cannot enter $val['name'] repeatedly*/ 
    }
}
$json_arr = array('status' => 'Ok','name' => $arr);
echo json_encode($json_arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM