代码点火器活动记录更新记录

时间:2014-04-14 21:12:01

标签: php codeigniter-2

我是新代码点火器,我按照视频教程创建初始代码 但是,我无法更新记录。

这是代码

类MY_Model扩展了CI_Model {

const DB_TABLE = "abstract";
const DB_TABLE_PK = "abstract";

public function __construct()
{
    $this->load->database(); 
}


private function insert()
{
    $this->db->insert($this::DB_TABLE, $this);
    $this->{$this::DB_TABLE_PK} = $this->db->insert_id();
}


private function update()
{
    $this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK);        
}

public function save()
{
    if(isset($this->{$this::DB_TABLE_PK}))
    {
        echo "inserting record";
        $this->update();
    }
    else
    {
        echo "updating record";
        $this->insert();
    }
}

}

班级出版物扩展了MY_Model {

const DB_TABLE = "publication";
const DB_TABLE_PK = "publication_id";


public $publication_id;
public $publication_name;

}

class Magazine扩展了CI_Controller {

public function db_update_publication_record()

{
    $this->load->model('Publication');
    $this->Publication->publication_id = 2;
    $this->Publication->publication_name = "update record -- it worked";
    $this->Publication->save();
    echo "<tt><pre>".  var_export($this->Publication, TRUE)."</pre></tt>";
}

}


当我尝试更新时,它没有找到DB_TABLE_PK并尝试插入, 如何在我的模型中设置主键,我可以更新记录。

请帮忙

2 个答案:

答案 0 :(得分:0)

您必须在第3个参数中放置数组或where字符串:

$this->db->update($table, $update, $where); 

类似的东西:

$this->db->update($this::DB_TABLE, $this, array($this::DB_TABLE_PK => $this->{$this::DB_TABLE_PK})));  

但我不确定&#34; $ this&#34;在第二个参数工作?

答案 1 :(得分:0)

这是Lynda教程“使用PHP CodeIgniter启动并运行”中的错误。 我遇到了同样的问题,但发现文档需要一个数组作为更新的第三个参数 - 教程只传递PK的名称,所以实际上它创建了一个SQL查询“... UPDATE ... WHERE PK = NULL“,它不会引发错误,而是会影响0行。文森特的上述答案正确地说明了这个函数需要如何编码。