how to update table using api in codeigniter

China☆狼群 提交于 2019-12-08 06:03:57

问题


I'm stuck at updating table row using api in codeigniter, i already have read tutorial from code tutsplus

but there's no spesific to do it, so i tried by myself and got stuck :-(

url request:

http://localhost/work/bnilife/v1/signup/user/post?nopol=a1b2c3d4e5&username=agus&password=kucingtikus&captcha=c12ds

Here's the json respon:

{
"error": "error :-( "
}

My Controller look like this below:

public function user_post()
  {
    date_default_timezone_set('Asia/Jakarta');
    $datestring ="%Y-%m-%d %H:%i:%s";
    $time       =time();
    $datetime   =mdate($datestring, $time);

    $data = array (
            'nopol'   => $this->input->get_post('nopol'),
            'username'   => $this->input->get_post('username'),
            'password'   => sha1($this->input->get_post('password')),
            'created_at' => $datetime,
            'updated_at' => $datetime
    );

    $result = $this->signup_m->signup_insert($data);
    if($result) {
      $this->response($data, 200);
    } else {
      $this->response(array('error' => 'error :-( '),400);
    }
  }

My model:

  public function signup_insert($data) {

  // Query to check whether username already exist or not
  $condition = "nopol=" . "'" . $data['nopol'] . "'" ;
  $this->db->where($condition);
  $this->db->update('user', $data); }

Is there any something wrong or misstype, thank you guys i'm new at this stuff.


回答1:


You can check codeigniter documentation how are working Database methods http://www.codeigniter.com/userguide3/database

public function signup_insert($data) {
  $this->db->where('nopol',$data['nopol']);
  return $this->db->update('user', $data); 
}

In your case you need and return else you can't use the method as $result as it will be equal to NULL..

  • Check and CI Form Validation library as you don't validate your input data (even escaped) it may generate problems.
  • And importantly, you should write proper method names: signup_insert should INSERT not UPDATE.



回答2:


'nopol' => $this->input->get_post('nopol') in this change to 'nopol' => $this->input->get_post('no_polis'),

also $this->db->where($condition) $condition is not defined.




回答3:


Like @svetlio said, i add some solution if nopol is typo(misstype) or null. it will return false, so i add some code to do it. like this below:

if ($this->db->affected_rows() === 1) {
    return true;
    } else {
    return false;
    }
  }

so it wont be like:

return $this->db->update('user', $data);


来源:https://stackoverflow.com/questions/29470161/how-to-update-table-using-api-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!