In this example we are going to show you how to insert data into database using CodeIgniter framework in PHP.
For insert data in MySQL using CodeIgniter first we have to create a table in the database
Contents
- Download Codeigniter 3
- Create a new Database
- Create a new table
- Create a new project name
- Create a new controller file
- Create a new model file
- Create a new view file
Steps to Insert Data into a Database:
- Create a new table in Mysql database
- Project folder name is codeIgniter
- Database name is sample
- Create new controller file in Path: codeIgniter\application\controllers\Save.php
- Create new view file in Path: codeIgniter\application\views\save.php
- Create new view file in Path: codeIgniter\application\models\Save_model.php
1. For creating a table the SQL query is:
CREATE TABLE crud (`id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,`first_name` varchar(30) NOT NULL,`last_name` varchar(30) NOT NULL,`email` varchar(30) NOT NULL,`mobile` varchar(30) NOT NULL);
2. Save.php (Controller)
<?phpclass Save extends CI_Controller{public function __construct(){/*call CodeIgniter's default Constructor*/parent::__construct();/*load database libray manually*/$this->load->database();/*load Model*/$this->load->model('Save_model');}/*Insert*/public function savedata(){/*load registration view form*/$this->load->view('save');/*Check submit button */if ($this->input->post('save')) {$data['first_name'] = $this->input->post('first_name');$data['last_name'] = $this->input->post('last_name');$data['email'] = $this->input->post('email');$data['mobile'] = $this->input->post('mobile');$response = $this->Save_model->saverecords($data);if ($response == true) {echo "Records Saved Successfully";} else {echo "Insert error !";}}}}?>
3. save.php (View)
<!DOCTYPE html><html><head><title>Registration form</title></head><body><form method="post" action="<?= base_url() ?>Crud/savedata"><table width="600" border="1" cellspacing="5" cellpadding="5"><tr><td width="230">First Name </td><td width="329"><input type="text" name="first_name" /></td></tr><tr><td>Last Name </td><td><input type="text" name="last_name" /></td></tr><tr><td>Email ID </td><td><input type="email" name="email" /></td></tr><tr><td>Mobile</td><td><input type="number" name="mobile" /></td></tr><tr><td colspan="2" align="center"><input type="submit" name="save" value="Save Data" /></td></tr></table></form></body></html>
4. Save_model.php (Model)
<?phpclass Save_model extends CI_Model{function saverecords($data){$this->db->insert('crud', $data);return true;}}?>
Finally enter this url in your browser : http://localhost/codeIgniter/index.php/Save/savedata
We hope this guide has been helpful. If you have any questions or need further assistance, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
0 Comments