Introduction
This tutorial is intended to introduce you to the CodeIgniter framework and the basic principles of MVC architecture. It will show you how a basic CodeIgniter application is constructed and for starters, I will assume that you already have installed CodeIgniter and you have a MySQL database installed on your webserver.
In this article, I will show you how to fetch data from s database and show it in a view in a tabular format in codeigniter.
See the following points.
- Create Table in MySQL database
My database name is "abc" and my table name is "country".
- CREATE TABLE country
- (
- Country_id int,
- country_name varchar(255)
- );
Here is my table structure;
- Database connectivity
You must first edit the file database.php that can be found in application/config/ folder. The important changes are these:
- $db['default']['hostname'] = 'localhost';
- $db['default']['username'] = 'root';
- $db['default']['password'] = '';
- $db['default']['database'] = 'abc';
- $db['default']['dbdriver'] = 'mysql';
- Autoload the database
If your application uses the database very much then you need to change the autoload.php that can also be found inside the application/config/ folder.
- $autoload['libraries'] = array('database');
- Config file
By default, CodeIgniter has one primary config file, located at application/config/config.php.
- $config['base_url'] = 'http://localhost/CI/';
CI is the folder where my application is present.
- The Model
In the Models we have the CRUD operations. I will create a model named select.php.
- <?php
- class select extends CI_Model
- {
- function __construct()
- {
-
- parent::__construct();
- }
-
- public function select()
- {
-
- $query = $this->db->get('country');
- return $query;
- }
- }
- ?>
- The Controller
I will create a model named home.php.
- <?php
- class home extends CI_Controller
- {
- public function index()
- {
-
- $this->load->database();
-
- $this->load->model('select');
-
- $data['h']=$this->select->select();
-
- $this->load->view('select_view', $data);
- }
- }
- ?>
- The view
To display the output we need a view named "select_view". The code will go something like this:
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Untitled Document</title>
- </head>
- <table border="1">
- <tbody>
- <tr>
- <td>Country Id</td>
- <td>Country Name</td>
- </tr>
- <?php
- foreach ($h->result() as $row)
- {
- ?><tr>
- <td><?php echo $row->Country_id;?></td>
- <td><?php echo $row->country_name;?></td>
- </tr>
- <?php }
- ?>
- </tbody>
- </table>
- <body>
- </body>
- </html>
- Output