【问题标题】:Please explain CodeIgniter ActiveRecord set() update()请解释 CodeIgniter ActiveRecord set() update()
【发布时间】:2014-03-26 21:28:21
【问题描述】:

我似乎无法在用户指南中找到明确的解释。

在 CodeIgniter 活动记录中,要更新表行,似乎需要做三件事:(1) 确定要更新的记录,(2) 定义需要更改的内容和 (3) 提交变化。

不知何故,无论我如何阅读手册,都不清楚。 https://www.codeigniter.com/userguide2/database/active_record.html#update

这似乎暗示“设置”是关于插入 - 这意味着在我的书中向表格中添加行。

而“更新”是关于“改变”现有信息。

对我有用的唯一方法是执行所有三个操作。

像这样:

$this->db->where('id',$userid);         //selecting the right user
$this->db->set($SubscriptionChoices);   //setting the new values to be written
$this->db->update('userprefs');         //Do it. Update table userprefs

【问题讨论】:

    标签: mysql codeigniter activerecord


    【解决方案1】:

    所以你所说的“设置”——它只是你正在更新的特定字段和你正在使用的值。就像从一个简单的表格来更新一个名字

        $updatedata = array(
            'first' => $this->input->post( 'first', TRUE ),
            'last' => $this->input->post( 'last', TRUE ),
            'statuscheck' => 'Name updated' 
            );
    

    然后将该数据和记录 id 传递给进行更新的方法

    function update( $id, $updatedata ) {
    
        $this->db->where( 'id', $id );
        $this->db->update( 'yourtablename', $updatedata );
    
        if ( $this->db->affected_rows() == '1' ) {return TRUE;}
    
        else {return FALSE;}
    
    } //
    

    请注意一些烦人的细节 - 如果您更新记录 - 使用相同的信息 - 就像在这种情况下,如果有人更新了记录但名字和姓氏相同 - 那么它将返回 'false' - 因为没有更新。

    因此,如果您在更新数组中包含一个始终不同的字段,例如日期时间秒数 - 那么您就不会遇到这个问题。

    【讨论】:

    • 是的,但我的意思是我无法让它发挥作用。它一直抱怨我必须使用“set()”。所以当你说->db->where 然后->db->update 我发现我必须使用->db->where 然后->db->set 然后->db->update。这就是我不明白的。
    • 上面的代码有效。听起来您传递给更新方法的数据数组存在问题。尝试一些简单的测试。
    【解决方案2】:

    有点晚了,但其他人可以得到帮助。

    你也可以在单个函数中使用它。

    $updatedata = array(
        'first' => $this->input->post( 'first', TRUE ),
        'last' => $this->input->post( 'last', TRUE ),
        'statuscheck' => 'Name updated' 
        );
    
    
    function update( $id, $updatedata ) {
    
        $where = array( 'id' => $id );
    
        $this->db->update( 'yourtablename', $updatedata , $where);
    
        if ( $this->db->affected_rows() == '1' ) {return TRUE;}
    
        else {return FALSE;}
    } //
    

    但您也可以使用下面提供 CRUD 功能的类,而不是使用它。

    https://github.com/avenirer/CodeIgniter-MY_Model

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 2017-10-19
      • 2018-01-30
      • 2018-07-06
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多