使用codeigniter将数据添加到数据库

时间:2012-09-04 16:12:55

标签: php database codeigniter content-management-system add

我目前正在尝试使用codeigniter向数据库添加数据。我已经使用active方法设置了一个注册页面,并尝试使用相同的方法添加新闻表单但是没有成功。

当我点击提交时,表示无法找到页面,并且网址显示控制器功能名称。当我故意将任何字段留空时,这是相同的。我检查了我的数据库,没有添加任何记录,也没有php日志错误。

以下是我的代码片段:

查看:

<?php echo form_open('add/add_article'); ?>
        <?php echo form_input('title', set_value('title', 'Title')); ?><br />
        <?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
        <?php echo form_input('author', set_value('author', 'Author')); ?>
        <?php echo form_submit('submit', 'Add Article'); ?>
        <?php echo validation_errors('<p class="error">' );?>
  <?php echo form_close(); ?>

控制器:

class Add extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->view('admin/add');
}

    public function add_article() {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'Title', 'trim|required');
        $this->form_validation->set_rules('content', 'Content', 'trim|required');
        $this->form_validation->set_rules('author', 'Author', 'trim|required');

        if($this->form_validation->run() == FALSE) {

        $this->index();

        }else{

            $this->load->model('news_model');
            if($query = $this->news_model->addArticle()) {
            $this->load->view('news');
            }else {
                $this->load->view('news');
        }
    }   
}
}

型号:

public function __construct() {
    parent::__construct();
}

        function addArticle() {
    $data =array(
    'title' => $this->input->post('title'),
    'content' => $this->input->post('content'), 
    'author' => $this->input->post('author'),
    'username' => $this->input->post('username'));

    $insert = $this->db->insert('news', $data);
    return $insert;
}
}

2 个答案:

答案 0 :(得分:3)

如果是丢弃页面的服务器,那么几乎可以肯定是URL问题而不是CI / PHP问题。

您的基本网址是否在配置文件中正确定义?您的.htaccess配置是否正确(旧配置可能是路由/从CI添加请求)?

尝试将以下操作添加到添加控制器,并直接导航到http://[base]/add/thetest

public function thetest() {
echo 'Controller accessed';
die;
}

如果仍然显示页面未找到,那么它不是您的代码,而是您的配置(服务器配置或CI)。

答案 1 :(得分:0)

而不是在模型中插入使用更新,如:

$insert = $this->db->update('news', $data);
return $insert;

我认为控制器中的这部分代码也是错误的(如果语句错误且没有数据发送到模型):

if($query = $this->news_model->addArticle()) {
            $this->load->view('news');
            }else {
                $this->load->view('news');
        }

试试这个:

$data =array(
    'title' => $this->input->post('title'),
    'content' => $this->input->post('content'), 
    'author' => $this->input->post('author'),
    'username' => $this->input->post('username')
);

$query = $this->news_model->addArticle($data);
if($query) 
{
   // query ok
   $this->load->view('news');
}
else {
   // no query
   $this->load->view('news');
}