phpjsoncodeigniterroutesinsert

Codeigniter Select JSON, Insert JSON


I have very simple users database: user_id, user_name, user_email

My model this:

class Users extends CI_Model {
private $table;
private $table_fields;
private $table_fields_join;

function __construct() {
    parent::__construct();

    $this->table = 'users';
    $this->table_fields = array(
            $this->table.'.user_id',
            $this->table.'.user_name',
            $this->table.'.user_email'
    );
    $this->table_fields_join = array();
}

function select(){
    $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));
    $this->db->from($this->table);

    $query = $this->db->get();

    if($query->num_rows() > 0){
        return $query->result();
    } else {
        return false;
    }
}

function insert($data) {
    $data = array(
       'user_name'  => $data['user_name'],
       'user_email' => $data['user_email']
    );

    $this->db->insert($this->table, $data);
}

My controller this:

class Users extends CI_Controller { 

function __construct(){
   parent::__construct();
   $this->load->model('users');
}
public function select(){
$data['query'] = $this->users->select(); 
$data = json_encode($data['query']);
echo $data;
}
public function insert($json){
  $data = json_decode($json);
  $this->users->insert($data);
  }
}

And this is my routing.php:

$route['default_controller'] = 'Welcome';
$route['users'] = 'users/select';
$route['users/insert/:(any)'] = 'users/insert';

I would like that 127.0.0.1/users/select give json. Example: [{"user_name":"user1","user_email":"user@user.de"}]

This JSON insert my table: 127.0.0.1/users/insert/[{"user_name":"user1","user_email":"user@user.de"}]

But my code is not working. :-(


Solution

  • You want to return json object in response, so it's required to set json type in response header. As given here

    public function select(){
      $data['query'] = $this->users->select(); 
      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($data['query']));
    }
    

    It is required to encode part as below for insert part. so you can use this generated url to call your insert.

    site_url('usres/insert/'.urlencode('[{"user_name":"user1","user_email":"user@user.de"}]'));
    

    your insert route should be as

    $route['users/insert/:(any)'] = 'users/insert/$1';

    your insert method should be updated as

    public function insert($json){
      $json = urldecode($json);
      $data = json_decode($json);
      $this->users->insert($data);
      }
    }