1

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;
    }

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

NB: i am using PDO

4

2 に答える 2

1

問題は、 $output が通過する必要がある配列であることです。お気に入り:

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);
    }
}

これは最後の応答用ですが、すべてが必要な場合は次のようにします。

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);
    }
}

1 行だけが必要な場合は、MySQL ステートメントに制限を追加します。

于 2013-09-14T01:37:25.617 に答える