Skip to content Skip to sidebar Skip to footer

How To Encode Multiple Rows From Mysql Into Json Using Php

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

Solution 1:

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

functiongetTopic($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 ($outputas$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:

functiongetTopic($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 ($outputas$o){
           $response[] = array('text'=>$o['original_title'],'test'=>$o['content']);
        }
        return json_encode($response);
    }
}

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

Solution 2:

$output is array of results. use a loop or if only one row u need do this:

functiongetTopic($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[0]['original_title'];
    $response['test'] = $output[0]['content'];
    return json_encode($response);
    //return $output;
}

Post a Comment for "How To Encode Multiple Rows From Mysql Into Json Using Php"