我有非常简单的用户数据库:user_id,user_name,user_email
我的模型是这样的:
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);
}
我的控制器是这样的:
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);
}
}
这是我的routing.php:
$route['default_controller'] = 'Welcome';
$route['users'] = 'users/select';
$route['users/insert/:(any)'] = 'users/insert';
我希望 127.0.0.1/users/select 给出 json。 示例:[{"user_name":"user1","user_email":"[电子邮件受保护]"}]
此 JSON 插入我的表:127.0.0.1/users/insert/[{"user_name":"user1","user_email":"[email protected]"}]
但是我的代码不起作用。 :-(
你想在响应中返回json对象,所以需要在响应头中设置
json
类型。如here所示
public function select(){
$data['query'] = $this->users->select();
$this->output
->set_content_type('application/json')
->set_output(json_encode($data['query']));
}
对于插入部分,需要对部分进行如下编码。这样你就可以使用这个生成的 url 来调用你的插入。
site_url('usres/insert/'.urlencode('[{"user_name":"user1","user_email":"[email protected]"}]'));
你的插入路线应该是
$route['users/insert/:(any)'] = 'users/insert/$1';
您的插入方法应更新为
public function insert($json){
$json = urldecode($json);
$data = json_decode($json);
$this->users->insert($data);
}
}