Convert codeigniter query to json? Convert codeigniter query to json? codeigniter codeigniter

Convert codeigniter query to json?


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.


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


As per latest CI standard use the following code in your controller file:

$this->output->set_content_type('application/json')->set_output(json_encode($arr));