views:

787

answers:

1

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?

+3  A: 

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.

Stephen Curran
Thanks a lot. I'm kind of new to codeigniter, much left to learn it's API, but now it's even more fun.
marko
No problem. Glad to help :-)
Stephen Curran