简体   繁体   中英

How get entry from two table of MySql using PHP to create Json array

I have two table in MySql, one for users information and another for new posts that post by users:

new_post table:

id  int(11)          
title   varchar(100)             
content text             
created_at  datetime             
url_image   varchar(300)             
user_id varchar(23)

users table:

uid int(11)          
unique_id   varchar(23)          
name    varchar(50)          
user_profile_image  varchar(300)             
email   varchar(100)             
encrypted_password  varchar(80)          
salt    varchar(10)      
created_at datatime

By using PHP I wanna create Json array. In Json array I want to return new_post entry and also user_profile_image that store in users table and I can access to it by user_id and unique_id.

I created PHP file and work fine for return new_post entry but I don't know how get user_profile_image and return with them.

It's my PHP code:

<?php
    //Create Database connection
    error_reporting(E_ALL ^ E_DEPRECATED);
    include 'conf.php';

    $pageNumber = $_GET['page_number'];

    $sql="select * from new_post order by ID DESC limit ".getpage($pageNumber);
    $result= mysql_query($sql);


    function getpage($p){
    $p--;
    return ($p*10).",10";
    }

    //Create an array
    $json_response = array();

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $row_array['id'] = $row['id'];
        $row_array['title'] = $row['title'];
        $row_array['content'] = ($row['content']); 
        $row_array['created_at'] = $row['created_at'];
        $row_array['url_image'] = $row['url_image'];


        //push the values in the array
        array_push($json_response,$row_array);
    }
    array_walk_recursive($json_response, function(&$val) {
    $val = utf8_encode($val);
});
    echo json_encode($json_response, JSON_UNESCAPED_SLASHES);

 print "ok";

?>

Any idea how to do it?

You can join the two tables in your query like:

 $sql="select * from new_post left join users on new_post.user_id = users.unique_id order by ID DESC limit ".getpage($pageNumber);

Now, you can use $row_array['user_profile_image']

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