Search code examples
phprestcodeignitercodeigniter-3codeigniter-restapi

php - Codeigniter Rest api simple CRUD


I have this problem with inserting data to MySQL which require POST method by using postman.

this function data_post() inserts data from database, but when I am trying to insert data raw data with postman

{"id":"2","name":"ropen","password":"pamela005"}

I am having this error on postman:

405 Method not Allowed

This is my Controller Users.php

public function data_post(){
    $params = [
        'id' => 1,
        'name' => 'John Doe',
        'password' => 'test'
    ];
    $resp = $this->user_model->data($params);
    $this->set_response($resp, REST_Controller::HTTP_CREATED);    
}

Model User_model.php

public function data($data){   
      $this->db->insert('user',$data);
   }

Solution

  • Hope this will help you :

    You have to get post data using $this->post() first , should be like this :

    Note : if your id column is autoincrement there is no need to add id in $params

    public function data_post()
    {
        $id = $this->post('id');
        $name = $this->post('name');
        $password = $this->post('password');
    
        $params = array('id' => $id,'name' => $name,'password' => $password);
        $resp = $this->user_model->data($params);
        $this->set_response($resp, REST_Controller::HTTP_CREATED);    
    } 
    

    For more : https://github.com/chriskacerguis/codeigniter-restserver#handling-requests