请解释CodeIgniter ActiveRecord set()update()

时间:2014-03-26 21:28:21

标签: mysql codeigniter activerecord

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

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

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

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

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

对我有用的唯一方法是做所有三个动作。

像这样:

$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

2 个答案:

答案 0 :(得分:0)

所以你称之为'set' - 它只是你要更新的特定字段和你正在使用的值。喜欢从简单的表格更新名称

    $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' - 因为没有更新。

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

答案 1 :(得分:0)

时间有点晚,但是其他人可以得到帮助。

您也可以在单个功能中使用它。

$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