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


Add data to the database using codeigniter

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

当我点击提交时,它说找不到页面,url显示控制器函数名。当我故意将任何字段留空时也是如此。我已经检查了我的数据库,没有添加任何记录,也没有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;
}
}

如果是服务器抛出了未找到的页面,那么几乎可以肯定是URL问题,而不是CI/PHP问题。

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

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

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

如果它仍然说没有找到页面,那不是你的代码,而是你的配置(服务器配置或CI)。

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

$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');
}