In part 4, we will learn how to add the new data via a form. Part 4 is the final part of the CodeIgniter3 tutorial series.
In part 3, we can read the data from a database using Query Builder from CodeIgniter. We create the database and table via phpMyadmin. We, also add a new record in the table via phpMyadmin. In this part, we will add a new record via an adding form.
Create a form
In this part, we will create a form for adding a new record into the news table which we create from Part 3. Below is the news table structure.
news table: id, title, slug and text
- The id will create automatically when the new data is added. so we don’t need to provide the id input field on our form.
- The title and text, we need to provide two fields for them on our form.
- The slug, we will derive the slug from the title in our model. So we don’t need to provide the slug field on our form.
Create a news form file
To create a form, we will create a new create.php under application/views/news directory.
Then copy the code below into the create.php
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="text" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
Notice that, we use the validation_errors function for reporting the error related to form validation. Also, we use the form_open function for creating an opening form tag with a base URL built from application/config/config.php and also, adding a hidden CSRF prevention field that contains methods that help you create a secure processing input data for security.
Add a new create method in a News controller
In Part 3, your News controller (application/controllers/news.php) looks like this:
<?php
class News extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('news/index', $data);
}
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('news/view', $data);
}
}
Now we will add a new create method into the News controller. The code is below.
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
Now the News controller (application/controllers/news.php) will look like this.
<?php
class News extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('news/index', $data);
}
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('news/view', $data);
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('news/create', $data);
} else {
$this->news_model->set_news();
$this->load->view('news/success');
}
}
}
In the News controller, we load the form helper and form validation library. Form helper will help to render a form in the create.php that we create above (application/views/news/create.php). The form validation library will do the form validation for us.
With the form validation library, we can simply set the validation rules for your form. In the code above, we use set_rules function to set the required rule for the title and text fields on our form.
Next, if all rules pass, we will call the set_news method from the News model. We will create the set_news method in the moment. Then we will show the success message on the browser. Let’s create a success message page.
Create a success message page
Create a new success.php under application/views/news directory. And write a success message in that file. I add “A new News is added.”.
Add a new set_news method into your News model
In Part 3, your News model looks like this.
<?php
class News_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_news($slug = FALSE)
{
if ($slug === FALSE) {
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}
Now, add a new set_news method from the code below into your News model (application/models/News_model.php).
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
Notice that, we load the URL helper so we can use the url_title function for deriving the slug from the title data.
Next, we prepare the data that we want to insert into our news table inside the $data array.
We use the post() method from the input library to make sure the data is sanitized and protecting you from the attacks from hackers. The input library is loaded by default so you don’t need to load manually in your News model.
Lastly, we insert our $data array into our database via Query Builder class.
Routing
Before the adding form page is working, you must add an extra rule to “application/config/routes.php” first.
Add the code below into the routes.php. We add “news/create” route to make sure CodeIgniter see “create” as a method instead of a news item’s slug.
// News routing
$route['news/create'] = 'news/create';
// We add these news routing earlier
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
// default routing
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
Time to add a new News item via your form
Now visit your browser and type your base URL and add “index.php/news/create” to the URL.
In my case, I type “http://codeigiter3-tutorial.local/index.php/news/create” on my browser while “http://codeigiter3-tutorial.local/” is my base URL for my CodeIgniter application.
Below is what my form looks like. When I add the title and text then hit the “Create news item” button, the data is added into my news table. And I see the success message page.
Visit your based URL and add “index.php/news/” to the URL to see the added news items. The News archive page we create in Part 3.
Conclusion
The CodeIgniter3 tutorial series covers the basic things for creating the simple web application with CodeIgniter and PHP.
If you follow my CodeIgniter series, you should be able to view all news items, view a single new item, adding a news item, and manipulate the data from the database via Query Builder class.
Useful links:
When you are developing your application with CodeIgniter, you will want to look for specific functions or helpful information for your development. I would suggest you check the links below. I use them all the time while I work with CodeIgniter.
- General Topics
- Reserved Names
- URI Routing
- Error Handling
- Profiling Your Application
- Managing your Applications
- Handling Multiple Environments
- Security
- PHP Style Guide
- Libraries
- Database Reference
- Query Builder Class
- Helper
That’s it for my CodeIgniter3 tutorial series.
CodeIgniter3 tutorial series:
- CodeIgniter3 tutorial part 1 – Installation and Configuration application
- CodeIgniter3 tutorial part 2 – Explain MVC pattern with a simple diagram
- CodeIgniter3 tutorial part 3 – Create a Model, View, and Controller. Create routing.
- CodeIgniter3 tutorial part 4 – Add new data into the database via an adding form.