CodeIgniter Basic Crud Application Part-I
06/04/2019 . 10 minutes, 3 seconds to read . Posted by Admin#MVCArchitecture #Model,View,Controller #htmlemail #codeigniteremail #XMLHandling #best-practices
Overview
In this part of the tutorial, we will go through the basics of the CodeIgniter.CodeIgniter is an MVC (Model, View, Controller) base framework widely used to enhance the development.
We will follow step by step process to create a complete basic crud application.
- Download and configure CodeIgniter
- Create Controller
- Create View
- Create Model
- Configure routes
- Auto Load Helpers
Requirements
- xammp or wamp server
- Codeigniter Setup
- PHP IDE (recommended vs code)
Step 1: Download CodeIgniter
To begin with CodeIgniter we need to download CodeIgniter setup. Click the link to download the setup https://www.codeigniter.com/download. I am using CodeIgniter version 3.1.1.0 you can download any version of your choice but it is better to use version 3.1. When you have downloaded extract the setup in public directory of your server folder. I am using xampp I have extracted in C:\xampp\htdocs. If you are using Wamp extract setup in C:\wamp\www. Once you have extracted the setup rename the folder CodeIgniter-3.1.10 to codeigniter-crud or you can choose any name for your project.let's run our project to check the initial output type localhost/codeigniter-crud or localhost/yourprojectname in your browser you will see following output mention below in the image on your screen.
If you don't get this output it means you have made any mistake in configuration review it and try again.
Step 2: Make Controller
The controller is the middle layer in CodeIgniter deal with business logic. It receives a request from view and sends this request to model and fetch the required data from the model and pass it to view.
Open project directory and go to application/controllers create a new file inside the controllers folder and name it 'User.php' and in 'User.php' make class 'User' it should extend base class CI_Controller.We will use the controller to request data from the model and pass it to view. The code is given below in the image.
/application/controllers/User.php
Now we will make a method in the 'User' Controller name "index" and in the method, we will simply echo "welcome".The method should be public so we can access it anywhere.
User.php
<?php
class User extends CI_Controller
{
public function index()
{
echo "welcome";
}
}
?>
We have defined a method to check output open browser and type or click http://localhost/codeigniter-crud/index.php/user or http://localhost/yourprojectname/index.php/user.You will get a "welcome" message on the screen check image given below.
output
Now we will write code to load a view in our controller. To load view first we need to create the view we will do it in next step let's write code to load the view. To load view write this line of code $this->load->view('viewpathandname'). view() is Codeigniter built-in function used to call the view, the load method is used to load core classes libraries and views. $this refers to an object of the current class.
User.php
<?php
class User extends CI_Controller
{
public function index()
{
$this->load->view('user/index');
}
}
?>
Let's try to run our code and see what will happen. Open the browser and type http://localhost/codeigniter-crud/index.php/user or http://localhost/yourprojectname/index.php/user. The following output will appear in our screen mention below in the image.
output
The above image shows an error because in our application 'user/index.php' view does not exist so before loading view we need to create a view. we will resolve this error in the next step by creating the view.
Step 3: Create View
The view in Codeigniter is outer layer used to display the user interface and output on the browser. The user directly interacts with the view and the view request data from the controller. In the view, we can write both PHP and HTML. Create a new folder in application/views and name it 'user' inside this folder create a new file 'index.php'. You can give any name of your choice, but it is better to specify the view name with the controller name so we can easily identify which view is used by which controller.
application/view/user/index.php
application/views/user/index.php
<h1>Hello World</h1>
We have added a code of line to our view. To load view open controller and write the following line of the code given below.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function index()
{
$this->load->view('user/index');
}
}
?>
Open browser and type or click http://localhost/codeigniter-crud/index.php/user or http://localhost/yourprojectname/index.php/user.
output
Later in step 2, we have had an error while loading the view in this step we have successfully loaded a view.
Step 4: Make Model
Model is the inner layer in Codeigniter use to manage data logic and contains database queries. Model is responsible for fetching the data from the server and return it to the controller in response to a request sent by the controller. To make a model open application/models create a file name it 'UserModel.php' in UserModel.php make a class UserModel extend it with CI_Model.
application/models/UserModel.php
The model may have many methods. Define a method index in the model and initialize an array of numbers in the index method and return this array.
application/models/UserModel.php
<?php
class UserModel extends CI_Model
{
public function index()
{
$Numbers=array('even'=>'2,4,6,...',
'odd'=>'3,6,9,...',
'natural'=>'1,2,3,...'
);
return $Numbers;
}
}
?>
We have returned an array of numbers in the model. Now we will get this array in the controller. To get the value of returned array in the controller first, we need to load the model. To load model add the following line of the code in the controller.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function index()
{
$this->load->model('UserModel');
$this->load->view('user/index');
}
}
?>
Now we need to call the index member function of the model ($this->UserModel->index()) to get the returned array in the controller. exit method is used to avoid compilation of the next line of the code.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function index()
{
$this->load->model('UserModel');
$data['numbers']=$this->UserModel->index();
exit;
$this->load->view('user/index');
}
}
?>
Output
Our next task is to pass this array to view and display the values of an array on the screen. We can pass data to view using $this->load->view('view name, array variable'),this is overloaded method contains two parameters. In the controller, we have set numbers as key we will use this key in the view to get data from the controller. The following line of code is used to pass the data from the controller to view.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function index()
{
$this->load->model('UserModel');
$data['numbers']=$this->UserModel->index();
$this->load->view('user/index',$data);
}
}
?>
The numbers was set as key in the controller and we already have passed the array in the view. Now in the view, we have to loop through the array and display values. We will use the foreach loop. To display data in the view we will use the following code.
application/views/user/index.php
<div>
<h3> Numbers</h3>
<?php foreach($numbers as $numberlist)
{?>
<h3><?=$numberlist?></h3>
<?php }?>
</div>
Output
In this step, we have passed data from model to controller and from controller to view. In the next step, we will set routes for our application.
Step 5: Configure /Set Routes
Routes In CodeIgniter used to respond to the URL request. The route consists of three optional parameters
- Controller
- Method
- Parameters
In this step we will not discuss routes in the detail, we will just set the default route for our controller. When you run the code first time without making any configurations as I mentioned in step 1 by default we get CodeIgniter welcome message on the screen this appears because in new application welcome controller is set as default controller. Open application/config/routes.php you will find following code given below in the image.
application/config/routes.php
In the above image, the welcome is the default controller and you can find it in application/controllers/. We already have created controller User, we want to make our controller default controller replace the welcome with the user. The code is given below.
application/config/routes.php
$route['default_controller'] = 'user';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
We have changed the default controller. Now let's run our application open browser and type http://localhost/codeigniter-crud/ or http://localhost/yourprojectname/
output
The above image shows that we have successfully changed the default controller to the user and the above image contains output produce by the user controller. Let's move to the next step and load helpers.
Step 6: Auto Load Helpers
Helpers are files in CodeIgniter contains functions used to perform tasks. In our application, we need URL helper to make links. Let's see how to autoload URL helper. Open application/config you will find autoload.php. Open the file and find helpers sections if you did not found, you can see the image given below.
application/config/autoload.php
Before loading the URL helper let's find the practical use of the URL helper. Go to view application/views/user/index.php and echo base_url(). base_url() is a built-in method defined in URL helper used to get the root path of the application. Run the code given below and see what happens.
application/views/user/index.php
<div>
<h3> Numbers</h3>
<?php foreach($numbers as $numberlist)
{?>
<h3><?=$numberlist?></h3>
<?php }?>
</div>
<div>
<h3><?= base_url()?></h3>
</div>
To run the above code simply type http://localhost/codeigniter-crud/ or http://localhost/yourprojectname/ in the browser and in output we will get error mention below in the image.
Output
In the above image, we got an error that specifies that base_url() function is not defined.
Let's load the URL helper to resolve the error. Open application/config/autoload.php and write following line of code to load the helper given below.
application/config/autoload.php
$autoload['helper'] = array('url');
Now run the application again and you will get the root path of your application as given below in the image
Output
We have successfully resolved the error by loading helper. Don't get confused with [::1] is the port address for the localhost if you get http://localhost/codeigniter-crud/ on your screen that is the same root path. In the next part, we will auto load libraries.
Important Points
- The Name of the Controller should be follow by the Capital Letter.
- The name of the controller file and class should be same.
- The Name of the Model should start with the capital letter.
- The name of the Model file and class should be same.
- Index() is the default method,call by its controller name.
- Always give similar name to model,view and controller.It will help you to identify interrelated model,controller and view.
- Take care of URL while making links.
In this part we have gone through the basics of CodeIgniter in the PART-II We will begin our crud application. For Part two follow the given link https://www.coderanks.com/crud/codeIgniter-part-II.
Hope you have learned basics of Codeigniter.
Thanks