Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert codeigniter query to json?

I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.

 $arr = array("one", "two", "three");
       $data["json"] = json_encode($arr);

Output

 <?php echo "var arr=".$json.";"; ?>
 var arr=["one","two","three"];

But when I try to convert a query codeigniter throws an error. What is it with that? This is the error message:

A PHP Error was encountered Severity: Warning Message: [json] (php_json_encode) type is unsupported, encoded as null

And the converted "query" result = I mean model method is like this:

{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null} 

I try to do like this

 $posts = $this->Posts_model->SelectAll();
       $data["posts"] = json_encode($posts); 

By the way, the model and method works just fine when I do it without json_encode.

Something I'm propably doing wrong, but the question is what?

like image 479
marko Avatar asked Mar 09 '10 21:03

marko


2 Answers

You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.

Your model code appears to be something like this :

function SelectAll()
{
    $sql = 'SELECT * FROM posts';
    // Return the result object
    return $this->db->query($sql);
}

It should be more like this :

function SelectAll()
{
    $sql = 'SELECT * FROM posts';
    $query = $this->db->query($sql);
    // Fetch the result array from the result object and return it
    return $query->result();
}

This will return an array of objects which you can encode in JSON.

The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.

like image 136
Stephen Curran Avatar answered Sep 21 '22 02:09

Stephen Curran


public function lastActivity()
{
    header("Content-Type: application/json");
    $this->db->select('*');
    $this->db->from('table_name');
    $query = $this->db->get();

    return json_encode($query->result());
}
like image 36
bamossza Avatar answered Sep 24 '22 02:09

bamossza