Você está na página 1de 21

Create Database and Table

First of all, we create database and table. For this article example, we will be creating database
named test. We will be creating a table named news inside the database test.

1 --
2 -- Create database `test`
3 --
4
5 CREATE DATABASE `test`;
6
7 use `test`;
8
9 --
10 -- Table structure for table `news`
11 --
12
13 CREATE TABLE IF NOT EXISTS `news` (
14 `id` int(11) NOT NULL AUTO_INCREMENT,
15 `title` varchar(128) NOT NULL,
16 `slug` varchar(128) NOT NULL,
17 `text` text NOT NULL,
18 PRIMARY KEY (`id`),
19 KEY `slug` (`slug`)
20 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
21
22 --
23 -- Dumping data for table `news`
24 --
25
26 INSERT INTO `news` (`id`, `title`, `slug`, `text`) VALUES
27 (1, 'Test', 'test', 'Hello World !!'),
28 (2, 'What is Lorem Ipsum?', 'what-is-lorem-ipsum', 'Lorem Ipsum is simply dummy text.');
I will present below the full code of controller, model, and views files. We will be adding, updating, deleting
news item to our database table. News item just contains title and text content.

Database Config Settings


After you create your database, you need to specify your database host, database name, database
username & database password in a database config file in codeigniter. The file is located
at application/config/database.php.
My database host is localhost, database name is test (as created by above sql query), database
username is root and database password is root.
Here is the config settings for this example:

File: application/config/database.php

1 $db['default'] = array(
2 'dsn' => '',
3 'hostname' => 'localhost',
4 'username' => 'root',
5 'password' => 'root',
6 'database' => 'test',
7 'dbdriver' => 'mysqli',
8 'dbprefix' => '',
9 'pconnect' => FALSE,
10 'db_debug' => (ENVIRONMENT !== 'production'),
11 'cache_on' => FALSE,
12 'cachedir' => '',
13 'char_set' => 'utf8',
14 'dbcollat' => 'utf8_general_ci',
15 'swap_pre' => '',
16 'encrypt' => FALSE,
17 'compress' => FALSE,
18 'stricton' => FALSE,
19 'failover' => array(),
20 'save_queries' => TRUE
21 );

Controller
(application/controllers/News.php)
First of all, we need a Controller which processes the input request from user, communicates with Model
and then loads appropriate Views file.

In the below Controller class, we have different functions (actions) for different tasks. Like,
the index()function is used for listing all news items, create() function is used to add a new news
item, edit()function is used to edit the news item, and delete() function is used to delete the news item.

1 <?php
2 class News extends CI_Controller {
3
4 public function __construct()
5 {
6 parent::__construct();
7 $this->load->model('news_model');
8 $this->load->helper('url_helper');
9 }
10
11 public function index()
12 {
13 $data['news'] = $this->news_model->get_news();
14 $data['title'] = 'News archive';
15
16 $this->load->view('templates/header', $data);
17 $this->load->view('news/index', $data);
18 $this->load->view('templates/footer');
19 }
20
21 public function view($slug = NULL)
22 {
23 $data['news_item'] = $this->news_model->get_news($slug);
24
25 if (empty($data['news_item']))
26 {
27 show_404();
28 }
29
30 $data['title'] = $data['news_item']['title'];
31
32 $this->load->view('templates/header', $data);
33 $this->load->view('news/view', $data);
34 $this->load->view('templates/footer');
35 }
36
37 public function create()
38 {
39 $this->load->helper('form');
40 $this->load->library('form_validation');
41
42 $data['title'] = 'Create a news item';
43
44 $this->form_validation->set_rules('title', 'Title', 'required');
45 $this->form_validation->set_rules('text', 'Text', 'required');
46
47 if ($this->form_validation->run() === FALSE)
48 {
49 $this->load->view('templates/header', $data);
50 $this->load->view('news/create');
51 $this->load->view('templates/footer');
52
53 }
54 else
55 {
56 $this->news_model->set_news();
57 $this->load->view('templates/header', $data);
58 $this->load->view('news/success');
59 $this->load->view('templates/footer');
60 }
61 }
62
63 public function edit()
64 {
65 $id = $this->uri->segment(3);
66
67 if (empty($id))
68 {
69 show_404();
70 }
71
72 $this->load->helper('form');
73 $this->load->library('form_validation');
74
75 $data['title'] = 'Edit a news item';
76 $data['news_item'] = $this->news_model->get_news_by_id($id);
77
78 $this->form_validation->set_rules('title', 'Title', 'required');
79 $this->form_validation->set_rules('text', 'Text', 'required');
80
81 if ($this->form_validation->run() === FALSE)
82 {
83 $this->load->view('templates/header', $data);
84 $this->load->view('news/edit', $data);
85 $this->load->view('templates/footer');
86
87 }
88 else
89 {
90 $this->news_model->set_news($id);
91 //$this->load->view('news/success');
92 redirect( base_url() . 'index.php/news');
93 }
94 }
95
96 public function delete()
97 {
98 $id = $this->uri->segment(3);
99
100 if (empty($id))
101 {
102 show_404();
103 }
104
105 $news_item = $this->news_model->get_news_by_id($id);
106
107 $this->news_model->delete_news($id);
108 redirect( base_url() . 'index.php/news');
109 }
110 }
Model
(application/models/News_model.php)
Model class communicates with the database. The main database logic is written here. This class is
responsible for interacting with database for data select, insert, update and delete purposes.

In the below Model class, get_news() function fetches/selects news items


by $slug name. get_news_by_id() function fetches news by it’s ID. set_news() function either edit or add
news item. delete_news() function delets any particular news item.

1 <?php
2 class News_model extends CI_Model {
3
4 public function __construct()
5 {
6 $this->load->database();
7 }
8
9 public function get_news($slug = FALSE)
10 {
11 if ($slug === FALSE)
12 {
13 $query = $this->db->get('news');
14 return $query->result_array();
15 }
16
17 $query = $this->db->get_where('news', array('slug' => $slug));
18 return $query->row_array();
19 }
20
21 public function get_news_by_id($id = 0)
22 {
23 if ($id === 0)
24 {
25 $query = $this->db->get('news');
26 return $query->result_array();
27 }
28
29 $query = $this->db->get_where('news', array('id' => $id));
30 return $query->row_array();
31 }
32
33 public function set_news($id = 0)
34 {
35 $this->load->helper('url');
36
37 $slug = url_title($this->input->post('title'), 'dash', TRUE);
38
39 $data = array(
40 'title' => $this->input->post('title'),
41 'slug' => $slug,
42 'text' => $this->input->post('text')
43 );
44
45 if ($id == 0) {
46 return $this->db->insert('news', $data);
47 } else {
48 $this->db->where('id', $id);
49 return $this->db->update('news', $data);
50 }
51 }
52
53 public function delete_news($id)
54 {
55 $this->db->where('id', $id);
56 return $this->db->delete('news');
57 }
58 }

Template Header
(application/views/templates/header.php)
This is a template file common for all pages. We call header in all pages.

<html>
1
<head>
2
<title>CodeIgniter Tutorial</title>
3
</head>
4
<body>
5
6
<h1>Simple CRUD</h1>
7
<p><a href="<?php echo site_url('news'); ?>">Home</a> | <a href="<?php echo site_url('news/create');
8
?>">Add News</a></p>

Template Footer
(application/views/templates/footer.php)
This is a template file common for all pages. We call footer in all pages.

1 <p><em>Copyright © 2016</em></p>
2 </body>
3 </html>

Index View
(application/views/news/index.php)
This view file is called by index() function of our Controller class. It lists out all the news item.

1 <h2><?php echo $title; ?></h2>


2
3 <table border='1' cellpadding='4'>
4 <tr>
5 <td><strong>Title</strong></td>
6 <td><strong>Content</strong></td>
7 <td><strong>Action</strong></td>
8 </tr>
9 <?php foreach ($news as $news_item): ?>
10 <tr>
11 <td><?php echo $news_item['title']; ?></td>
12 <td><?php echo $news_item['text']; ?></td>
13 <td>
14 <a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View</a> |
15 <a href="<?php echo site_url('news/edit/'.$news_item['id']); ?>">Edit</a> |
16 <a href="<?php echo site_url('news/delete/'.$news_item['id']); ?>" onClick="return confirm('Are you sure
17 you want to delete?')">Delete</a>
18 </td>
19 </tr>
20 <?php endforeach; ?>
</table>

Detail View
(application/views/news/view.php)
This view file is called by view() function of our Controller class. It prints a particular news item.

1 <?php
2 echo '<h2>'.$news_item['title'].'</h2>';
3 echo $news_item['text'];

Add View
(application/views/news/create.php)
This view file is called by create() function of our Controller class. It prints a form to add news item.

1 <h2><?php echo $title; ?></h2>


2
3 <?php echo validation_errors(); ?>
4
5 <?php echo form_open('news/create'); ?>
6 <table>
7 <tr>
8 <td><label for="title">Title</label></td>
9 <td><input type="input" name="title" size="50" /></td>
10 </tr>
11 <tr>
12 <td><label for="text">Text</label></td>
13 <td><textarea name="text" rows="10" cols="40"></textarea></td>
14 </tr>
15 <tr>
16 <td></td>
17 <td><input type="submit" name="submit" value="Create news item" /></td>
18 </tr>
19 </table>
20 </form>

Edit View
(application/views/news/edit.php)
This view file is called by edit() function of our Controller class. It prints a form to edit news item.
1 <h2><?php echo $title; ?></h2>
2
3 <?php echo validation_errors(); ?>
4
5 <?php echo form_open('news/edit/'.$news_item['id']); ?>
6 <table>
7 <tr>
8 <td><label for="title">Title</label></td>
9 <td><input type="input" name="title" size="50" value="<?php echo $news_item['title'] ?>" /></td>
10 </tr>
11 <tr>
12 <td><label for="text">Text</label></td>
13 <td><textarea name="text" rows="10" cols="40"><?php echo $news_item['text'] ?></textarea></td>
14 </tr>
15 <tr>
16 <td></td>
17 <td><input type="submit" name="submit" value="Edit news item" /></td>
18 </tr>
19 </table>
20 </form>

Add Success View


(application/views/news/success.php)
This view file is called after a new news item is added to database. This file is called in create() function of
our Controller class.

1 <p>News added successfully!</p>

Config Routes
(application/config/routes.php)
Routing rules are defined here. Routes can either be specified using wildcards or Regular Expressions.

1 $route['news'] = 'news';
2 $route['news/create'] = 'news/create';
3
4 $route['news/edit/(:any)'] = 'news/edit/$1';
5
6 $route['news/view/(:any)'] = 'news/view/$1';
7 $route['news/(:any)'] = 'news/view/$1';
Now, you can access your application as http://your-website.com/news.
When you open your project in browser, you will get something like below image:
Download Source Code from GitHub
Hope this helps. Thanks.

Share this:

Create Database and Table


First of all, we create database and table. For this article example, we will be creating database
named test. We will be creating a table named news inside the database test.

1 --
2 -- Create database `test`
3 --
4
5 CREATE DATABASE `test`;
6
7 use `test`;
8
9 --
10 -- Table structure for table `news`
11 --
12
13 CREATE TABLE IF NOT EXISTS `news` (
14 `id` int(11) NOT NULL AUTO_INCREMENT,
15 `title` varchar(128) NOT NULL,
16 `slug` varchar(128) NOT NULL,
17 `text` text NOT NULL,
18 `user_id` int(11) NOT NULL DEFAULT '0',
19 PRIMARY KEY (`id`),
20 KEY `slug` (`slug`)
21 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
22
23 --
24 -- Dumping data for table `news`
25 --
26
27 INSERT INTO `news` (`id`, `title`, `slug`, `text`, `user_id`) VALUES
28 (1, 'Test', 'test', 'Hello World !!', 1),
29 (2, 'What is Lorem Ipsum?', 'what-is-lorem-ipsum', 'Lorem Ipsum is simply dummy text.', 1),
30 (3, 'My test', 'my-test', 'hello there', 2);
31
32 --
33 -- Table structure for table `user`
34 --
35
36 CREATE TABLE `user` (
37 `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
38 `firstname` varchar(255) NOT NULL,
39 `lastname` varchar(255) NOT NULL,
40 `email` varchar(255) NOT NULL,
41 `password` varchar(255) NOT NULL,
42 `updated_at`varchar(255) NULL DEFAULT NULL,
43 PRIMARY_KEY (`id`)
44 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
45
46 --
47 -- Indexes for table `user`
48 --
49 ALTER TABLE `user`
50 ADD UNIQUE KEY `user_email_unique` (`email`);
I will present below the full code of controller, model, and views files. We will be adding, updating, deleting
news item to our database table. News item just contains title and text content.

Database Config Settings


After you create your database, you need to specify your database host, database name, database
username & database password in a database config file in codeigniter. The file is located
at application/config/database.php.
My database host is localhost, database name is test (as created by above sql query), database
username is root and database password is root.
Here is the config settings for this example:

File: application/config/database.php

1 $db['default'] = array(
2 'dsn' => '',
3 'hostname' => 'localhost',
4 'username' => 'root',
5 'password' => 'root',
6 'database' => 'test',
7 'dbdriver' => 'mysqli',
8 'dbprefix' => '',
9 'pconnect' => FALSE,
10 'db_debug' => (ENVIRONMENT !== 'production'),
11 'cache_on' => FALSE,
12 'cachedir' => '',
13 'char_set' => 'utf8',
14 'dbcollat' => 'utf8_general_ci',
15 'swap_pre' => '',
16 'encrypt' => FALSE,
17 'compress' => FALSE,
18 'stricton' => FALSE,
19 'failover' => array(),
20 'save_queries' => TRUE
21 );
==========================================================

Here’s the full code of controller, model, and views files. In this example, we will be having two controller
class. One will be for User and the other will be for News. Similarly, there will be two model classes
(User_model and News_model).
Let’s first create User controller and model class for user login and registration.

User Controller
(application/controllers/User.php)
Controller processes the input request from user, communicates with Model and then loads appropriate
Views file.

In the below Controller class, we have different functions (actions) for different tasks. Like,
the login()function is used for logging users, register() function is used to register users in the application.

1 <?php
2 class User extends CI_Controller {
3
4 public function __construct()
5 {
6 parent::__construct();
7 $this->load->model('user_model');
8 $this->load->helper(array('form', 'url'));
9 $this->load->library(array('session', 'form_validation'));
10 }
11
12 public function index()
13 {
14 $this->register();
15 }
16
17 public function register()
18 {
19 $this->form_validation->set_rules('firstname', 'First Name',
20 'trim|required|alpha|min_length[3]|max_length[50]');
21 $this->form_validation->set_rules('lastname', 'Last Name',
22 'trim|required|alpha|min_length[3]|max_length[50]');
23 $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[user.email]');
24 $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[cpassword]|md5');
25 $this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required');
26
27 $data['title'] = 'Register';
28
29 if ($this->form_validation->run() === FALSE)
30 {
31 $this->load->view('templates/header', $data);
32 $this->load->view('user/register');
33 $this->load->view('templates/footer');
34
35 }
36 else
37 {
38 if ($this->user_model->set_user())
39 {
40 $this->session->set_flashdata('msg_success','Registration Successful!');
41 redirect('user/register');
42 }
43 else
44 {
45 $this->session->set_flashdata('msg_error','Error! Please try again later.');
46 redirect('user/register');
47 }
48 }
49 }
50
51 public function login()
52 {
53 $email = $this->input->post('email');
54 $password = $this->input->post('password');
55
56 $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
57 $this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
58
59 $data['title'] = 'Login';
60
61 if ($this->form_validation->run() === FALSE)
62 {
63 $this->load->view('templates/header', $data);
64 $this->load->view('user/login');
65 $this->load->view('templates/footer');
66
67 }
68 else
69 {
70 if ($user = $this->user_model->get_user_login($email, $password))
71 {
72 /*$user_data = array(
73 'email' => $email,
74 'is_logged_in' => true
75 );
76
77 $this->session->set_userdata($user_data);*/
78
79 $this->session->set_userdata('email', $email);
80 $this->session->set_userdata('user_id', $user['id']);
81 $this->session->set_userdata('is_logged_in', true);
82
83
84 $this->session->set_flashdata('msg_success','Login Successful!');
85 redirect('news');
86 }
87 else
88 {
89 $this->session->set_flashdata('msg_error','Login credentials does not match!');
90
91 $currentClass = $this->router->fetch_class(); // class = controller
92 $currentAction = $this->router->fetch_method(); // action = function
93
94 redirect("$currentClass/$currentAction");
95 //redirect('user/login');
96 }
97 }
98 }
99
100 public function logout()
101 {
102 if ($this->session->userdata('is_logged_in')) {
103
104 //$this->session->unset_userdata(array('email' => '', 'is_logged_in' => ''));
105 $this->session->unset_userdata('email');
106 $this->session->unset_userdata('is_logged_in');
107 $this->session->unset_userdata('user_id');
108 }
109 redirect('news');
}
}

User Model
(application/models/User_model.php)
Model class communicates with the database. The main database logic is written here. This class is
responsible for interacting with database for data select, insert, update and delete purposes.

In the below Model class, get_user() function fetches/selects users by $id. get_user_login() function
fetches user by checking username and password. set_user() function either edit or add
user. delete_user() function deletes any particular user.
1 <?php
2 class User_model extends CI_Model {
3
4 public function __construct()
5 {
6 $this->load->database();
7 }
8
9 public function get_user($id = 0)
10 {
11 if ($id === 0)
12 {
13 $query = $this->db->get('user');
14 return $query->result_array();
15 }
16
17 $query = $this->db->get_where('user', array('id' => $id));
18 return $query->row_array();
19 }
20
21 public function get_user_login($email, $password)
22 {
23 $query = $this->db->get_where('user', array('email' => $email, 'password' => md5($password)));
24 //return $query->num_rows();
25 return $query->row_array();
26 }
27
28 public function set_user($id = 0)
29 {
30 $data = array(
31 'firstname' => $this->input->post('firstname'),
32 'lastname' => $this->input->post('lastname'),
33 'email' => $this->input->post('email'),
34 'password' => $this->input->post('password'),
35 'updated_at' => date('Y-m-d H:i:s')
36 );
37
38 if ($id == 0) {
39 return $this->db->insert('user', $data);
40 } else {
41 $this->db->where('id', $id);
42 return $this->db->update('user', $data);
43 }
44 }
45
46 public function delete_user($id)
47 {
48 $this->db->where('id', $id);
49 return $this->db->delete('user');
50 }
51
52 }

User Registration View


(application/views/user/register.php)
<p>
<?php echo $this->session->flashdata('verify_msg'); ?>
</p>

<h4>User Registration Form</h4>


1
2
<?php $attributes = array("name" => "registrationform");
3
echo form_open("user/register", $attributes);?>
4
<table>
5
<tr>
6
<td><label for="name">First Name</label></td>
7
<td><input name="firstname" placeholder="First Name" type="text" value="<?php echo set_value('fname');
8
?>" /> <span style="color:red"><?php echo form_error('firstname'); ?></span></td>
9
</tr>
10
<tr>
11
<td><label for="name">Last Name</label></td><td><input name="lastname" placeholder="Last Name"
12
type="text" value="<?php echo set_value('lname'); ?>" /> <span style="color:red"><?php echo
13
form_error('lastname'); ?></span></td>
14
</tr>
15
<tr>
16
<td><label for="email">Email ID</label></td><td><input class="form-control" name="email"
17
placeholder="Email-ID" type="text" value="<?php echo set_value('email'); ?>" /> <span style="color:red"><?php
18
echo form_error('email'); ?></span></td>
19
</tr>
20
<tr>
21
<td><label for="subject">Password</label></td><td><input class="form-control" name="password"
22
placeholder="Password" type="password" /> <span style="color:red"><?php echo form_error('password');
23
?></span></td>
24
</tr>
25
<tr>
26
<td><label for="subject">Confirm Password</label></td><td><input class="form-control" name="cpassword"
27
placeholder="Confirm Password" type="password" /> <span style="color:red"><?php echo form_error('cpassword');
28
?></span></td>
29
</tr>
30
<tr>
31
<td></td>
32
<td><button name="submit" type="submit">Signup</button></td>
33
</tr>
34
</table>
<?php echo form_close(); ?>

<p style="color:green; font-style:bold"><?php echo $this->session->flashdata('msg_success'); ?></p>


<p style="color:red; font-style:bold"><?php echo $this->session->flashdata('msg_error'); ?></p>

User Login View


(application/views/user/login.php)

1 <p>
2 <?php echo $this->session->flashdata('verify_msg'); ?>
3 </p>
4
5 <h4>User Login Form</h4>
6
7 <?php $attributes = array("name" => "loginform");
8 echo form_open("user/login", $attributes);?>
9 <table>
10 <tr>
11 <td><label for="email">Email</label></td><td><input class="form-control" name="email"
12 placeholder="Email-ID" type="text" /> <span style="color:red"><?php echo form_error('email'); ?></span></td>
13 </tr>
14 <tr>
15 <td><label for="subject">Password</label></td><td><input class="form-control" name="password"
16 placeholder="Password" type="password" /> <span style="color:red"><?php echo form_error('password');
17 ?></span></td>
18 </tr>
19 <tr>
20 <td></td>
21 <td><button name="submit" type="submit">Login</button></td>
22 </tr>
23 </table>
24 <?php echo form_close(); ?>

<p style="color:green; font-style:bold"><?php echo $this->session->flashdata('msg_success'); ?></p>


<p style="color:red; font-style:bold"><?php echo $this->session->flashdata('msg_error'); ?></p>

News Controller
(application/controllers/News.php)
In the below Controller class the index() function is used for listing all news items, create() function is used
to add a new news item, edit() function is used to edit the news item, and delete() function is used to
delete the news item.
While creating and editing news items, first of all, we check if the user is logged in or not. If not logged in,
the user is redirected to login page.

1 if (!$this->session->userdata('is_logged_in')) {
2 redirect(site_url('user/login'));
3 } else {
4 $data['user_id'] = $this->session->userdata('user_id');
5}
Similarly, we also check if the logged in user is actually trying to edit/delete his/her own article (article
added by him/her) or trying to edit/delete others’ article. If trying to edit others’ article then the user is
redirected to news index page.

1 if ($data['news_item']['user_id'] != $this->session->userdata('user_id')) {
2 $currentClass = $this->router->fetch_class(); // class = controller
3 redirect(site_url($currentClass));
4}
Here’s the full source code for News Controller.

1 <?php
2 class News extends CI_Controller {
3
4 public function __construct()
5 {
6 parent::__construct();
7 $this->load->model('news_model');
8 $this->load->helper('url_helper');
9 $this->load->library('session');
10 $this->load->library('pagination');
11 }
12
13 public function index()
14 {
15 $data['news'] = $this->news_model->get_news();
16 $data['title'] = 'News archive';
17
18 $this->load->view('templates/header', $data);
19 $this->load->view('news/index', $data);
20 $this->load->view('templates/footer');
21 }
22
23 public function view($slug = NULL)
24 {
25 $data['news_item'] = $this->news_model->get_news($slug);
26
27 if (empty($data['news_item'])) {
28 show_404();
29 }
30
31 $data['title'] = $data['news_item']['title'];
32
33 $this->load->view('templates/header', $data);
34 $this->load->view('news/view', $data);
35 $this->load->view('templates/footer');
36 }
37
38 public function create()
39 {
40 if (!$this->session->userdata('is_logged_in')) {
41 redirect(site_url('user/login'));
42 } else {
43 $data['user_id'] = $this->session->userdata('user_id');
44 }
45
46 $this->load->helper('form');
47 $this->load->library('form_validation');
48
49 $data['title'] = 'Create a news item';
50
51 $this->form_validation->set_rules('title', 'Title', 'required');
52 $this->form_validation->set_rules('text', 'Text', 'required');
53
54 if ($this->form_validation->run() === FALSE) {
55 $this->load->view('templates/header', $data);
56 $this->load->view('news/create');
57 $this->load->view('templates/footer');
58 } else {
59 $this->news_model->set_news();
60 $this->load->view('templates/header', $data);
61 $this->load->view('news/success');
62 $this->load->view('templates/footer');
63 }
64 }
65
66 public function edit()
67 {
68 if (!$this->session->userdata('is_logged_in')) {
69 redirect(site_url('user/login'));
70 } else {
71 $data['user_id'] = $this->session->userdata('user_id');
72 }
73
74 $id = $this->uri->segment(3);
75 //$id = $this->input->post('id');
76
77 if (empty($id)) {
78 show_404();
79 }
80
81 $this->load->helper('form');
82 $this->load->library('form_validation');
83
84 $data['title'] = 'Edit a news item';
85 $data['news_item'] = $this->news_model->get_news_by_id($id);
86
87 if ($data['news_item']['user_id'] != $this->session->userdata('user_id')) {
88 $currentClass = $this->router->fetch_class(); // class = controller
89 redirect(site_url($currentClass));
90 }
91
92 $this->form_validation->set_rules('title', 'Title', 'required');
93 $this->form_validation->set_rules('text', 'Text', 'required');
94
95 if ($this->form_validation->run() === FALSE) {
96 $this->load->view('templates/header', $data);
97 $this->load->view('news/edit', $data);
98 $this->load->view('templates/footer');
99 } else {
100 $this->news_model->set_news($id);
101 //$this->load->view('news/success');
102 redirect( site_url('news') );
103 }
104 }
105
106 public function delete()
107 {
108 if (!$this->session->userdata('is_logged_in')) {
109 redirect(site_url('user/login'));
110 }
111
112 $id = $this->uri->segment(3);
113
114 if (empty($id)) {
115 show_404();
116 }
117
118 $news_item = $this->news_model->get_news_by_id($id);
119
120 if ($news_item['user_id'] != $this->session->userdata('user_id')) {
121 $currentClass = $this->router->fetch_class(); // class = controller
122 redirect(site_url($currentClass));
123 }
124
125 $this->news_model->delete_news($id);
126 redirect( base_url() . 'index.php/news');
127 }
128 }

News Model
(application/models/News_model.php)
In the below Model class, get_news() function fetches/selects news items by $slug name and user
id. get_news_by_id() function fetches news by it’s ID. set_news() function either edit or add news
item. delete_news() function delets any particular news item.

1 <?php
2 class News_model extends CI_Model {
3
4 public function __construct()
5 {
6 $this->load->database();
7 }
8
9 public function record_count()
10 {
11 return $this->db->count_all('news');
12 }
13
14 public function get_news($slug = FALSE)
15 {
16 if ($slug === FALSE)
17 {
18 $query = $this->db->get_where('news', array('user_id' => $this->session->userdata('user_id')));
19 return $query->result_array(); // $query->result(); // returns object
20 }
21
22 $query = $this->db->get_where('news', array('slug' => $slug, 'user_id' => $this->session->userdata('user_id')));
23 return $query->row_array(); // $query->row(); // returns object
24
25 // $query->num_rows(); // returns number of rows selected, similar to counting rows
26 // $query->num_fields(); // returns number of fields selected
27 }
28
29 public function get_news_by_id($id = 0)
30 {
31 if ($id === 0)
32 {
33 $query = $this->db->get('news');
34 return $query->result_array();
35 }
36
37 $query = $this->db->get_where('news', array('id' => $id));
38 return $query->row_array();
39 }
40
41 public function set_news($id = 0)
42 {
43 $this->load->helper('url');
44
45 $slug = url_title($this->input->post('title'), 'dash', TRUE);
46
47 $data = array(
48 'title' => $this->input->post('title'), // $this->db->escape($this->input->post('title'))
49 'slug' => $slug,
50 'text' => $this->input->post('text'),
51 'user_id' => $this->input->post('user_id'),
52 );
53
54 if ($id == 0) {
55 //$this->db->query('YOUR QUERY HERE');
56 return $this->db->insert('news', $data);
57 } else {
58 $this->db->where('id', $id);
59 return $this->db->update('news', $data);
60 }
61 }
62
63 public function delete_news($id)
64 {
65 $this->db->where('id', $id);
66 return $this->db->delete('news'); // $this->db->delete('news', array('id' => $id));
67
68 // error() method will return an array containing its code and message
69 // $this->db->error();
70 }
71 }

Template Header
(application/views/templates/header.php)
This is a template file common for all pages. We call header in all pages. User email is displayed if the
user is logged in.
1 <html>
2 <head>
3 <title>CodeIgniter Tutorial</title>
4 </head>
5 <body>
6
7 <h1>Simple CRUD</h1>
8 <p>
9 <a href="<?php echo site_url('news'); ?>">Home</a> |
10 <a href="<?php echo site_url('news/create'); ?>">Add News</a> |
11
12 <?php if ($this->session->userdata('is_logged_in')) {
13 echo '<b>Logged in as:</b> ' . $this->session->userdata('email');
14 echo ' | ' . "<a href=" . site_url('user/logout') . ">Logout</a>";
15 } else {
16 ?>
17 <a href="<?php echo site_url('user/register'); ?>">Register</a> |
18 <a href="<?php echo site_url('user/login'); ?>">Login</a>
19 <?php } ?>
20 </p>

Template Footer
(application/views/templates/footer.php)
This is a template file common for all pages. We call footer in all pages.

1 <p><em>Copyright © 2016</em></p>
2 </body>
3 </html>

Index View
(application/views/news/index.php)
This view file is called by index() function of our Controller class. It lists out all the news item. The Edit and
Delete link are only displayed for logged in users.

1 <h2><?php echo $title; ?></h2>


2
3 <table border='1' cellpadding='4'>
4 <tr>
5 <td><strong>Title</strong></td>
6 <td><strong>Content</strong></td>
7 <td><strong>Action</strong></td>
8 </tr>
9 <?php foreach ($news as $news_item): ?>
10 <tr>
11 <td><?php echo $news_item['title']; ?></td>
12 <td><?php echo $news_item['text']; ?></td>
13 <td>
14 <a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View</a>
15
16 <?php if ($this->session->userdata('is_logged_in')) { ?>
17 |
18 <a href="<?php echo site_url('news/edit/'.$news_item['id']); ?>">Edit</a> |
19 <a href="<?php echo site_url('news/delete/'.$news_item['id']); ?>" onClick="return confirm('Are you sure
20 you want to delete?')">Delete</a>
21 <?php } // end if ?>
22
23 </td>
24 </tr>
25 <?php endforeach; ?>
</table>

Detail View
(application/views/news/view.php)
This view file is called by view() function of our Controller class. It prints a particular news item.

1 <?php
2 echo '<h2>'.$news_item['title'].'</h2>';
3 echo $news_item['text'];

Add View
(application/views/news/create.php)
This view file is called by create() function of our Controller class. It prints a form to add news item.

1 <h2><?php echo $title; ?></h2>


2
3 <?php echo validation_errors(); ?>
4
5 <?php echo form_open_multipart('news/create'); ?>
6
7 <table>
8 <tr>
9 <td><label for="title">Title</label></td>
10 <td><input type="input" name="title" size="50" /></td>
11 </tr>
12 <tr>
13 <td><label for="text">Text</label></td>
14 <td><textarea name="text" rows="10" cols="40"></textarea></td>
15 </tr>
16 <tr>
17 <td></td>
18 <td><input type="submit" name="submit" value="Create news item" /></td>
19 </tr>
20 </table>
21
22 <input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
23 </form>

Edit View
(application/views/news/edit.php)
This view file is called by edit() function of our Controller class. It prints a form to edit news item.

1 <h2><?php echo $title; ?></h2>


2
3 <?php echo validation_errors(); ?>
4
5 <?php echo form_open('news/edit/'.$news_item['id']); ?>
6 <table>
7 <tr>
8 <td><label for="title">Title</label></td>
9 <td><input type="input" name="title" size="50" value="<?php echo $news_item['title'] ?>" /></td>
10 </tr>
11 <tr>
12 <td><label for="text">Text</label></td>
13 <td><textarea name="text" rows="10" cols="40"><?php echo $news_item['text'] ?></textarea></td>
14 </tr>
15 <tr>
16 <td></td>
17 <td><input type="submit" name="submit" value="Edit news item" /></td>
18 </tr>
19 </table>
20
21 <input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
22 </form>

Add Success View


(application/views/news/success.php)
This view file is called after a new news item is added to database. This file is called in create() function of
our Controller class.

1 <p>News added successfully!</p>

Config Routes
(application/config/routes.php)
Routing rules are defined here. Routes can either be specified using wildcards or Regular Expressions.

1 $route['user'] = 'user';
2 $route['user/register'] = 'user/register';
3
4 $route['news'] = 'news';
5 $route['news/create'] = 'news/create';
6
7 $route['news/edit/(:any)'] = 'news/edit/$1';
8
9 $route['news/view/(:any)'] = 'news/view/$1';
10 $route['news/(:any)'] = 'news/view/$1';
Now, you can access your news application as http://your-website.com/news. User login page will
be found at http://your-website.com/user/login & user registration page will be
at http://your-website.com/user/register.
Here is an example page of logged in user with some news added:

Download Source Code from GitHub


Hope this helps. Thanks.

Você também pode gostar