简体   繁体   中英

Getting data from database showing it as json response

In mysql table I have set of record. I want to fetch them wanna showlike below json response.

"results":[

    {
        "timestamp":"2014-03-04 17:26:14",
        "id":"440736785698521089",
        "category":"sports",
        "username":"chetan_bhagat",
        "displayname":"Chetan Bhagat"
     }

I am getting above values ie timestamp,id,category,username from database. How can I show the result in form of json response like above?

UPDATE:

I fetch data in this way:

$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
            if (mysqli_connect_errno())
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
                return;
            }   
            $today = date("Ymd");           

            $result = mysqli_query($con,"SELECT url,img_url,sentiment,title,category from frrole_cateogry_article where category='".$category."' AND today <= '".$today."' AND title != '' AND img_url != '' order by url desc limit 3 ");
            while ($row = @mysqli_fetch_array($result))
            {
                $url = $row['url'];
                $img_url = $row['img_url'];
                $screen_name = $row['screen_name'];
            }

Fetch your results in the traditional way:

$data['results'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

Then convert it all to JSON. Bam!

$results = json_encode($data);

This is far easier than trying to format JSON in your SQL query.

See for more details:


Since you're use mysqli instead of PDO, and using it in a procedural fashion, you'd fetch rows a different way:

while ($data['results'][] = mysql_fetch_assoc($result));

Then you can json_encode() as I showed above.

try this...

        $con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
        if (mysqli_connect_errno())
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            return;
        }   
        $today = date("Ymd");           

        $result = mysqli_query($con,"SELECT url,img_url,sentiment,title,category from frrole_cateogry_article where category='".$category."' AND today <= '".$today."' AND title != '' AND img_url != '' order by url desc limit 3 ");
        while ($row = @mysqli_fetch_array($result))
        {
            json_encode($row);             
        }

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