【问题标题】:how to update table using api in codeigniter如何在codeigniter中使用api更新表
【发布时间】:2015-06-10 18:50:29
【问题描述】:

我一直在使用 codeigniter 中的 api 更新表格行, 我已经阅读了code tutsplus的教程

但是没有什么特别的方法, 所以我自己尝试并卡住了:-(

网址请求:

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

这是 json 响应:

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

我的控制器如下所示:

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);
    }
  }

我的模特:

  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); }

是否有任何错误或错误输入, 谢谢你们 我是这方面的新手。

【问题讨论】:

  • 1)。你真正想要做什么 2)你已经在你的模型中写了// Query to check whether username already exist or not,而不是检查你直接更新你的字段 3)if($result) 这没有任何意义

标签: php codeigniter api insert-update


【解决方案1】:

您可以查看 codeigniter 文档是如何工作的数据库方法 http://www.codeigniter.com/userguide3/database

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

在您的情况下,您需要并返回,否则您不能将该方法用作 $result,因为它将等于 NULL..

  • 检查和 CI 表单验证库,因为您不验证输入数据(甚至转义),它可能会产生问题。
  • 重要的是,您应该编写正确的方法名称:signup_insert 应该是 INSERT 而不是 UPDATE。

【讨论】:

  • 感谢您的解释,它有效。老兄。再次感谢。 @svetlio
【解决方案2】:

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

$this->db->where($condition) $condition 也没有定义。

【讨论】:

    【解决方案3】:

    就像@svetlio 所说, 如果 nopol 是拼写错误(misstype)或 null,我会添加一些解决方案。 它会返回假, 所以我添加了一些代码来做到这一点。 像下面这样:

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

    所以不会是这样的:

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

    【讨论】:

      猜你喜欢
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2013-06-17
      • 2011-12-30
      • 2019-12-20
      相关资源
      最近更新 更多