In this section, We'll understand how to insert data into database using Controller Model
and View
. We'll use tbl_users table to insert, display, update and delete data.
create a table named "tbl_users".
CREATE TABLE tbl_users(
id INT AUTO_INCREMENT,
name VARCHAR(32) NOT NULL,
email VARCHAR(32) NOT NULL,
contact_no VARCHAR(32) NOT NULL,
primary key(id)
);
Using a text editor, create a controller called User.php. In it, place this code and save it to your application/controllers/
directory:
<?php
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
/* Load form validation library */
$this->load->library('form_validation');
/* Validation rule */
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('user_form');
}
else {
$this->load->model('user_model');
$this->user_model->save();
$success = "Submit successfully!";
$this->load->view('user_form', compact('success'));
}
}
}
?>
Using a text editor, create a form called user_form.php. In it, place this code and save it to your application/views/
directory:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-2"></div>
<div class="col-md-8" style="margin-top:20px">
<?php
echo form_open('user/index');
echo validation_errors();
if (isset($success))
echo '<p>'.$success.'</p>';
?>
<div class="form-group">
<label for="email">Name:</label>
<input type="text" id="name" name="name" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" id="email" name="email" />
</div>
<div class="form-group">
<label for="contact_no">Contact Number:</label>
<input type="text" id="contact_no" name="contact_no" />
</div>
<button type="submit" class="btn btn-success">Submit</button>
<?php
echo form_close();
?>
</div>
<div class="col-md-2"></div>
</body>
</html>
Using a text editor, create a model called User_model.php. In it, place this code and save it to your application/models/
directory:
php
class User_model extends CI_Model
{
public function save()
{
$data['name'] = $this->input->post('name');
$data['email'] = $this->input->post('email');
$data['contact_no'] = $this->input->post('contact_no');
$this->db->insert('tbl_users', $data);
}
}
To try your form, visit your site using a URL similar to this one:
http://localhost/codeigniter/index.php/user/index