Php Can';t插入数据库codeigniter,但可以更新
我的CodeIgniter有问题 我正在学习NETTUTS教程,学习如何使用CI构建CMS。我设置了相同的函数save来更新和保存数据库中的新项Php Can';t插入数据库codeigniter,但可以更新,php,mysql,codeigniter,Php,Mysql,Codeigniter,我的CodeIgniter有问题 我正在学习NETTUTS教程,学习如何使用CI构建CMS。我设置了相同的函数save来更新和保存数据库中的新项 public function save($data, $id = NULL){ // Set timestamps if ($this->_timestamps == TRUE) { $now = date('Y-m-d H:i:s'); $id || $data['created']
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
$id = $this->db->insert_id();
$this->db->set($data);
$this->db->insert($this->_table_name);
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
问题是,更新工作正常,但插入工作不正常
以下是他正在调用的控制器函数:
public function edit ($id = NULL)
{
// Fetch a page or set a new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'page could not be found';
}
else {
$this->data['page'] = $this->page_m->get_new();
}
// Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
// Set up the form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->page_m->array_from_post(array('title','slug','body','parent_id'));
$this->page_m->save($data, $id);
redirect('admin/page');
}
// Load the view
$this->data['subview'] = 'pages/admin/page/edit';
$this->load->view('pages/admin/_layout_main', $this->data);
}
我想我给了你足够的背景希望它对你有用:
if (!$id) {
//$this->db->set($data);
$this->db->insert($this->_table_name, $data);
$id = $this->db->insert_id();
}
编辑:
我看了那个教程,里面有一些有趣的信息。但我强烈敦促您考虑更新和插入作为单独的方法。这样容易多了。如果节省几行代码会使应用程序更难构建,那么这并不值得。总是先追求可读性。你设置了一个条件,如果由于某种原因id没有通过-它不会给你一个错误-它将继续插入重复的记录。(悲伤的脸)是的,我对CI还是新手,所以我这样做了,但在未来我将用不同的方法来做这些仍然是最好的codeigniter教程:从CI 1.7到CI 2.0有一些细微的变化,但在其他方面它们仍然非常可靠。发生了同样的事情,它没有在我的数据库中插入任何内容,最糟糕的是,CI没有给我一个好的错误日志消息,以找出它为什么不存储在数据库中。
else {
$this->data['page'] = $this->page_m->get_new();
$id = NULL;
}