如何连接code多行从MySQL到使用PHP JSON [英] how to encode multiple rows from mysql into json using php

查看:170
本文介绍了如何连接code多行从MySQL到使用PHP JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想带code数据的所有行我从DB进入JSON,然后在客户端处理,但我似乎无法得到它work..My code低于

I am trying to encode all the rows of data i get from the DB into JSON and then process it at the client side but i can't seem to get it to work..My code is below

function getTopic($conn){
    $response = array("error" => 0);
    $qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
    $result = $conn->prepare($qry);
    $result->execute();
    if($result->rowCount() > 0){
        $output = $result->fetchall();
        $response['text'] = $output['original_title'];
        $response['test'] = $output['content'];
        return json_encode($response);
        //return $output;
    }

然后我尝试打印的var_dump($响应),但我得到空值。虽然如果我的var_dump($输出)我在array..accessing阵列获取所有的行是这里的问题now..i认为

Then i try to print the var_dump($response) but i get null values.. Although if i var_dump($output) i get all the rows in an array..accessing the array is the problem here now..i think

注:我使用的PDO

推荐答案

的问题是$输出是,你需要经过一个数组。这样的:

The problem is the $output is an array that you need to go through. Like:

function getTopic($conn){
    $response = array("error" => 0);
    $qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
    $result = $conn->prepare($qry);
    $result->execute();
    if($result->rowCount() > 0){
        $output = $result->fetchall();
        foreach ($output as $o){
           $response['text'] = $o['original_title'];
           $response['test'] = $o['content'];
        }
        return json_encode($response);
    }
}

这是最后的反应,但如果你希望所有,这样做:

This is for the last response, but if you want all, do:

function getTopic($conn){
    $response = array('error'=>0);
    $qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
    $result = $conn->prepare($qry);
    $result->execute();
    if($result->rowCount() > 0){
        $output = $result->fetchall();
        foreach ($output as $o){
           $response[] = array('text'=>$o['original_title'],'test'=>$o['content']);
        }
        return json_encode($response);
    }
}

如果你只想要一个行加限制你的MySQL声明。

If you are only want one row add a limit to your MySQL statement.

这篇关于如何连接code多行从MySQL到使用PHP JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆