Post REST 中的方法 API 使用 codeigniter

Post method in REST API using codeigniter

当我使用以下方法并将正文键作为 fail(未定义的键)传递并且一些值在 return 中获取 pass 消息并且在 [=24 中插入空行时=], 如何验证?

我在 REST 中使用的函数 API,

function categories_POST() {
    $title = $this->post('title');
    $no = $this->post('no');
    $id= $this->post('id');

    $this->load->model('model_check');
    $msg = $this->model_check->addDetails($title , $no , $id);
    $this->response($msg);
}

我的模型,

function addDetails($x, $y, $z) {
    $check = "INSERT INTO categories (title,no,id) VALUES ('$x','$y','$z')";
    $query = $this->db->query($check);
    if($this->db->affected_rows() > 0) {
        return "pass";
    } else {
        return "fail";
    }
}

在 CodeIgniter

中获取 post 值的两种方法
$title = $this->input->post('title');
$no = $this->input->post('no');
$id= $this->input->post('id');



    $this->load->model('model_check');
    $msg = $this->model_check->addDetails($title , $no , $id);
    $this->response($msg);

extract($_POST);

然后直接访问post名字

   $this->load->model('model_check');
    $msg = $this->model_check->addDetails($title , $no , $id);
    $this->response($msg);

最好的方法是直接访问模型文件(而不是控制器)中的 post 值

不需要在模型函数中传递 POST 值。

如果您有更多疑问,请问我

老实说,您最好使用查询构建器并(取决于您遵循的风格(fat/skinny controllers/models))让模型处理 $this->post()处理中。

这是 Phil Sturgeons/Chris A 的休息服务器吗?

类似于:

function categories_post() {  // doesn't need to be POST()

    $this->load->model('model_check');
    $msg = $this->model_check->addDetails()
    if ($msg)
    {
        $this->response([
            'status'            => TRUE,
            'message'           => 'pass'
          ], REST_Controller::OK);
    }
    // default to fail
   $this->response([
        'status'            => FALSE,
        'message'           => 'fail'
      ], REST_Controller::HTTP_BAD_REQUEST);
}

您的模特,

function addDetails() {
    // this only checks to see if they exist
    if (!$this->post() || !$this->post('x') || !$this->post('y') || !$this->post('z')) {
        return false;
    };
    $insert = array(
      'x' => $this->post('x'),
      'y' => $this->post('y'),
      'z' => $this->post('z'),
    );


    if($this->db->insert('categories', $insert))
    {
        return true;

    } 
    return false;  // defaults to false should the db be down

}

如果你的意思是 form_validation 你可以用这个代替上面的。

function addDetails() {

    $this->load->library('form_validation');
    $this->form_validation->set_rules('x', 'X', 'required');
    $this->form_validation->set_rules('y', 'Y', 'required');
    $this->form_validation->set_rules('z', 'Z', 'required');

    if ($this->form_validation->run() == true)
    {
        $insert = array(
          'x' => $this->post('x'),
          'y' => $this->post('y'),
          'z' => $this->post('z'),
        );

        if($this->db->insert('categories', $insert))
        {
            return true;

        }
    } 
    return false;  // defaults to false should the db be down

}

这很冗长,有更短的方法可以做到这一点,但我宁愿让它容易理解。