无法插入数据库codeigniter但可以更新

时间:2013-09-18 14:27:13

标签: php mysql codeigniter

我在使用CodeIgniter时遇到了麻烦。

我正在关注如何使用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'] = $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);
}

我想我给了你足够的背景

1 个答案:

答案 0 :(得分:3)

希望它适合你:

if (!$id) {
    //$this->db->set($data);
    $this->db->insert($this->_table_name, $data);
    $id = $this->db->insert_id();
}

编辑:

else {
    $this->data['page'] = $this->page_m->get_new();
    $id = NULL;
}