Insert values of a form to database in codeigniter

后端 未结 1 710
天涯浪人
天涯浪人 2021-01-26 03:19

Sorry for My Ignorace but codeigniter is new for me. SO I dont know how to insert values to database. So my basic question is I want to understand that how values are inserted f

相关标签:
1条回答
  • 2021-01-26 03:48

    Look, a few points...don't name your controller Form...that's a bad idea...and all of this is pretty much straight from the documentation. I'm not reposting your viewcode... This is VERY basic code I'm posting here, and there are better ways of doing things, and probably some more things you are going to want to process in your controller before moving on, but this should at least get you started. Also, don't name your models and controllers things like "form" and "formsubmit" ...it's just not good practice...name them things like "User" and "Users."

    Also, don't forget to adjust your routes file accordingly.

    This is your controller

    <?php
    
    class User extends CI_Controller {
        public function index()
                {
            $this->load->helper(array('form', 'url'));
    
            $this->load->library('form_validation');
            $this->form_validation->set_rules('username', 'Username', 'required');
            $this->form_validation->set_rules('password', 'Password', 'required',
                                                array('required' => 'You must provide a %s.')
                                        );
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required');
    
            if ($this->form_validation->run() === FALSE)
            {
                $this->load->view('index_view', $data);
            }
            else
            {
                $this->load->model('Users_model');
                $this->Users_model->insert_user();
                $this->load->view('your_success_view');
            }
        }
    }
    ?>
    

    This is your model:

    <?php
    
    class Users_model extends CI_Model
    {
        public function insert_user()
        {    
            $data = array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                'email' => $this->input->post('email')
            );
    
            // users is the name of the db table you are inserting in
            return $this->db->insert('users', $data);
        }   
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题