phpcodeignitermodel-view-controllerurl-routingform-submit

CodeIgniter's form_open() is not routing to the intended controller method


I am currently trying to add data to the database using CodeIgniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.

When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when I purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.

Here is my snippets of code:

View:

<?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(); ?>

Controller:

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

Model:

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

public 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;
}

Solution

  • If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.

    Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?

    Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest

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

    If it still says page not found it's not your code, it's your config (either server config or CI).