creating a web application with PHP and CodeIgniter - part3
Home » BLOG » Web development » Creating a Web Application with PHP and CodeIgniter – Part 3

Creating a Web Application with PHP and CodeIgniter – Part 3

category:  CodeIgniter, Web development
[Sassy_Social_Share] 5 min read

In part 3, we will learn how to create a Model, View, and Controller in CodeIgniter. Also, we will learn the routing.

Setting up a model

Models are the place where you retrieve, insert, and update data in your database. Basically, the Models represent your data from your database.

The example in this part 3, it comes from CodeIgniter tutorial website. If you like to read more detail, you can visit that tutorial. In part 3, I intend to keep it short.

News section

We will create a News section for creating a Model. Make sure you set your database settings in application/config/database.php. If you don’t set up the CodeIgniter application yet, you should visit CodeIgniter tutorial part 1 then come back to this part 3.

Assume you already create your database via phpMyadmin and set your database settings in application/config/database.php.

# Create a new News table

Create a new News table in your database via phpMyadmin.

CREATE TABLE news (
        id int(11) NOT NULL AUTO_INCREMENT,
        title varchar(128) NOT NULL,
        slug varchar(128) NOT NULL,
        text text NOT NULL,
        PRIMARY KEY (id),
        KEY slug (slug)
);

Then insert some data into the News table. You can insert the new data via phpMyadmin for now. So we will have some data to render on the view page.

# Create a new News_model.php

Create a new News_model.php under application/models directory and put the code below in it.

<?php
class News_model extends CI_Model
{

    public function __construct()
    {
        $this->load->database();
    }
}

To create a new Model, we need to extend the CI_Model class. Then loads the database library in the __construct method. With class, when it first loads, the __contruct method will be called first. After loading the database library, we can use the database class object through the  $this->db object.

# Create a get_news method

Now, we can use the Query Builder for retrieving the data from your database. In News_model.php, we create a get_news method with the code below.

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();
}

So in your News_model.php, your code will look 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();
    }
}

Notice that, the $slug variable is not sanitized before running the query. This is because of Query Builder does this for you.

Display the news

Now, the queries are written in the News model. Next, we want to display the news on the news page. To do that, we need to create the News controller first.

Create a News controller

Create a News.php under application/controllers directory. Then put the code below into the News.php.

<?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();
        }

        public function view($slug = NULL)
        {
                $data['news_item'] = $this->news_model->get_news($slug);
        }
}

In __construct method, we calls the constructor of its parent class which is CI_Controller.

Then we load the News model class so that all methods in this News controller can call the News model class.

Lastly, we load the URL helper which we will use for working with URLs later. In CodeIgniter, you will load the library or helper when you need it. That’s why CodeIgniter is lightweight and perform very fast.

Passing the data to the view

In the index method, we retrieve the data via our News model and store it in $data array. But we don’t pass the data to the view yet. This can be done by passing the data via $this->load->view().

So in the News controller (application/controllers/news.php), replace the index method with this code.

public function index()
{
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';

        $this->load->view('news/index', $data);
}

Create a view to render the news items

Now, the data from our News model is passing to the View via the News controller. Next, we need to create the view file for rendering the news items.

Create a new index.php under application/views/news directory. Then add the code below into the index.php.

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

<?php foreach ($news as $news_item): ?>

        <h3><?php echo $news_item['title']; ?></h3>
        <div class="main">
                <?php echo $news_item['text']; ?>
        </div>
        <p><a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article</a></p>

<?php endforeach; ?>

The template mixes between PHP and HTML. However, you can use a template language you like. You can use CodeIgniter’s Template Parser or any third party parser.

Create a view to render a single news item

Now, we have the view to render all news items. But we need a view to render only a single news item as well. To do that, we will update the view method in the News.php under application/controllers/news.php. Replace the view method with the code below.

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);
}

Next, we will create a view.php under application/views/news/view.php and put the following code in this file.

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

What your application file structure looks like

At this point, your application file structure will look like this.

  • application folder
    • models folder
      • News_model.php
    • controllers folder
      • news.php
  • webroot/public folder
    • news folder
      • index.php
      • view.php

Routing

Routing is how the URLs look like for each request. CodeIgniter reads the routing rule from top to bottom. You can modify your routing rules in application/config/routes.php.

Very often in MVC, you will see URL patterns that match:

http://example.com/[controller-class]/[controller-method]/[arguments]

URL patterns in MVC

http://example.com is your base URL where you set it in appliation/config/config.php.

For our News section, we will define our routing rules in application/config/routes.php as below.

// our custom routing rules for News section
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';

// default routing 
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

See the result on the browser

After adding the code into the routes.php, navigate to your browser and enter your base URL and then followed by index.php/news. Then see the result.

In my case, I enter “http://codeigiter3-tutorial.local/index.php/news” at my browser while “http://codeigiter3-tutorial.local/” is my base URL. I see my result below.

news codeigniter

When I click on the View article link on the News archive page, it will render a single news item below. The link will be “http://codeigiter3-tutorial.local/index.php/news/news1”.

news single item

Conclusion

In CodeIgniter tutorial part 3, we learn how to create Model, View, and Controllers for the News section example. We learn how to define the custom routing rules for the News section. And, we learn how to connect to the database and retrieving the data via Query Builder from CodeIgniter. In CodeIgniter tutorial part 4, we will learn how to add a new data set to your news table using an adding form.

CodeIgniter3 tutorial series: