Code Igniter is a simple and easy to use framework for PHP. If you are looking for a PHP framework to start with, to know how the MVC model or the basic functionality of a framework in general work, Code Igniter or CI is the perfect one for you. It has a lot of community support and also you can learn a lot by going through its proper documentation and user guide at https://ellislab.com/codeigniter/user-guide/toc.html and more specifically about database functions/queries at https://ellislab.com/codeigniter/user-guide/database/. You can download the latest CI at http://www.codeigniter.com/. If you face any difficulty in installing CI to your server or local machine, you can check out the user guide link mentioned above to help you out. There are already many tutorials about creating a CRUD app in CI, but I found them to be a bit difficult for a fresher. All they do is give you the code with a touch of some advance level functions like CI validation etc and don’t really explain which code relates to what in a MVC manner. I’ll try to do exactly that below, keeping the application simple, easy to understand in as less words as possible and hoping that I don’t miss anything crucial. So, here we go….
In an MVC model, MVC stands for M-Model, V-View, C-Controller. The model files are used for database handling i.e. queries, the view files are used to display data to the user and the main controller files are used to write the code to let the model and the view interact with each other and also add logic to your functions, if any. In addition to just using the MVC model, I’ll also try to explain using layouts or common template file structure.
CRUD stands for Create, Read, Update, Delete, i.e. we’ll create an entry in the database, read that entry, edit/update that entry and lastly delete that entry from the database. Now, conventionally you would like to be able to add an entry, but we’ll start first by reading an entry to boast the morale. To do this we’ll first need a database. You can download the employees/person database which I’ve used from here:
Download Employees database
This database has the following columns:
id (Auto increment),
You can also create your own test database from generatedata.com/, which is a free website service to create 100 records database for you in a flash.
I assume that you know how to import this database in your server/phpmyadmin-MySql.
The general configuration of our CI installation is as follows:
$config[‘base_url’] = ‘http://localhost/crud_ci’;
$config[‘index_page’] = ”;
$db[‘default’][‘hostname’] = ‘localhost’;
$db[‘default’][‘username’] = ‘root’;
$db[‘default’][‘password’] = ”;
$db[‘default’][‘database’] = ‘crud_db’;
$db[‘default’][‘dbdriver’] = ‘mysql’;
$db[‘default’][‘dbprefix’] = ”;
$db[‘default’][‘pconnect’] = TRUE;
$db[‘default’][‘db_debug’] = TRUE;
$db[‘default’][‘cache_on’] = FALSE;
$db[‘default’][‘cachedir’] = ”;
$db[‘default’][‘char_set’] = ‘utf8’;
$db[‘default’][‘dbcollat’] = ‘utf8_general_ci’;
$db[‘default’][‘swap_pre’] = ”;
$db[‘default’][‘autoinit’] = TRUE;
$db[‘default’][‘stricton’] = FALSE;
$route[‘default_controller’] = “crud”;
Replace the inner content with:
RewriteCond $1 !^(index\.php|assets|img)
RewriteRule ^(.*)$ ./index.php/$1 [L]
Next, open your root folder, open the application folder, open the controllers folder and create a file crud.php . On your local machine, using XAMPP, the path would be like this:
Where crud_ci is your root folder.
We’ll first create a class Crud which will extend the class CI_Controller. All of our code will be written in this class. The first function we’ll create is the __construct function and load the files common to all the rest of the functions in this class, so they are readily available for them and we don’t have to load the files every time we create a new function. Check out the code below:
Next will be our index function. this is the function which is called when accessing the base url, so we’ll redirect this to show the list of employees from our database, which will be our main view.
Now, the main function:
As you can see, we’ve called the view_data() function from our crud_model file. Now we’ll create that function. Open your root folder, open the application folder, open the models folder and create a file crud_model.php . On your local machine, using XAMPP, the path would be like this:
Where crud_ci is your root folder.
in this crud_model file we’ll create a Crud_model class which will extend the CI_Model class. All the functions would be written in this class. The first being the __construct and then our view_data() function.
The $query variable is to get all the rows and columns of the table employees and then the $result variable will contain the result in an array. We’ll then return this result to the view function in the controller using the return statement. The return statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Now, if you see the view() function in the controller file again, you’ll notice that this array result is associated with the $dataArray[“empArr”]. The named key of an array in the controller is available in the view as a variable. In this case the “empArr” will be available in the view as $empArr. We’ll then add this $dataArray to the $dataArr[“page_view”] array along with the view file for displaying our output. The third parameter is set to “true”, which means that you wish to pass it into the layout as $page_view. Then we’ll load the final view containing our layout and the result of our query using:
As you’ll notice, we’ve loaded the view view_crud_view. This will be called in the layout where our main content would be. The other files common to all the app functions are header, sidebar and footer.
Now we’ll create the view file to view our results.
Open your root folder, open the application folder, open the views folder, create a folder named “crud” and create a file view_crud_view.php in it. On your local machine, using XAMPP, the path would be like this:
Where crud_ci is your root folder.
In the view_crud_view file, copy and paste the following code:
#ID First Name Last Name Email ID Phone no. Company Action edit?id= " >
As you’ll notice the empArr key is available to us as $empArr array variable. If you want to see what this variable contains, uncomment the code before the foreach loop and reload the page. Make sure you comment it as before when you’ve finished checking it out. Now, go back to your views folder and create another folder named layout. Open and create the following files in: layout.php header.php sidebar.php footer.php in the layout.php file, copy-paste the following code:
in the header.php file, copy-paste the following code:
In your sidebar.php file, copy-paste the following code:
In your footer.php file, copy-paste the following code:
The layout part is done and we don’t need to touch it again. I haven’t used much style or even included a css stylesheet to make it look pleasing. I’m sorry for that but my main motive here is to show you the working of a CRUD application and not user interface development. If done correctly, you should see something like the below image: Now, we’ll create the “add” function, which will enable us to add data to the end of this list. In our crud.php controller file, add the following code:
Again, we are adding the data which we’ll receive from the add_crud_view.php form into the $dataArray array and then adding this array into the $dataArr[“page_view”] array key, and then finally passing all of it to the layout. The model function we have called here is add_data($data), where $data will be whatever you’ll pass in the add_data() function in the controller, in our case it’s $dataArray. In our crud_model.php file, add the following code:
We’ll also have to create a corresponding add_crud_view in which we’ll build a form to post data to the controller. In our views folder, open the crud folder and create a file name add_crud_view.php. In this file add the following code:
That’s it. you are done with the add functionality. When you’ll click on any of the Add Data button, you should see the following screen: Now we’ll move on to the most important and complex functionality of all, the ‘edit’ of an entry functionality. It’s divided into two tasks. The first task is to take the user to a screen where he/she can edit or alter the details of the selected person and second is to update the database with those altered details. If you check our view_crud_view file again, you’ll notice that we’ve anchored the Edit button to the url: “edit?id=“. This means that when clicked on a list entry having the id say “1”, we’ll be redirected to the link http://localhost/crud_ci/crud/edit?id=1. Knowing the id of the entry is crucial to display it’s corresponding value sin the edit screen for the user to edit. Now there are many other supposedly secure ways like using form and post, jQuery-AJAX etc to do this rather than getting the id via url, but then I’ll have to change the heading of this tutorial and remove the word “simple” from it. Anyhow, to take the user to the edit screen, first create a. edit() function in the controller i.e. in the crud.php file. Check out the function below:
As you can see, we’ve received the specific id of the person using $_GET Super Global variable $_GET. Then we’ve called our query through the edit_data($id) function from the crud_model. The result of that query has been received in the controller as an array and we’ve assigned that result to the $output variable, which is further assigned to the $dataArray as per their respective key-value relation. Again the $dataArray is assigned to the $dataArr[“page_view”] array and submitted to the layout for final display.
Now, we’ll create the edit_data($id) function in the crud_model.php file and run our query in it to fetch the details of the person corresponding to the id. check out the function below:
The query itself is quite clear. Although the main thing to notice here is that we returned the query to the controller in a row_array(). This is why we haven’t applied the foreach loop in the controller to get the $output values. row_array() returns an single dimension array result i.e. an associative array and result_array() returns double/multiple dimension array result.
If you’ll check the controller file again, we’ve also loaded the edit_crud_view file. this is the view which will display the current values of the person and also allow us to edit them. In your C:\xampp\htdocs\crud_ci\application\views\crud folder, create a file view_crud_view.php and copy-paste the below code into it:
It’s clear from the action attribute of the form that the submit will post all these details to the update function in the copntroller, which we’ll create next.
If the above is done correctly, then when clicked on the ‘Edit’ button in our main view with respect to the id say 3, you should see the screen below:
All the fields are editable except the ‘id’ field.
Now, whatever you would’ve edited will be submitted to the update function in the crud.php controller file. Therefore, open your crud.php file, create a update() function in it and copy-paste the following code in it:
The update function is also quite simple. We get our id. We also get our edited data and assign it to the respective database fields. And then we pass all this data to the update_data($id, $data) function in our crud_model file. If everything goes well, the user is redirected to the main view.
As aforementioned, we’ll now create the update_data($id, $data) function in our crud_model.php file. Open the file, create update_data($id, $data) and copy-paste the below code:
That’s it for the complete update functionality. We don’t need any view for the update function as it’s a server side action. The user can check out the updated person record in the main view.
The last functionality we have to achieve is to delete a record from the database through view. If you’ll check our main view one last time, you’ll notice that we’ve anchored the Delete button to the delete function of our crud controller file. Again we’ve passed the corresponding id of the record through the url using the ‘?’ query string, so that our controller will know which id to delete.
In our crud.php controller file, create the function delete_data($id) and copy-paste the below code into it:
In this function we are receiving the id through get method; we could also get using the $_GET Super Global variable but this here is the actual and right way in Code Igniter to write the get method. The id is then passed to the delete_data($id) function in the crud_model.php file, where we’ll rite the query to delete the record. Lastly the user will be redirected to the main view.
Now, in the crud_model.php file we’ll write the last snippet of our code which will conclude our CRUD app. In the crud_model.php model file, create the delete_data($id) function and copy-paste the below code into it:
This concludes this tutorial. I hope my language was easy to understand and not that boring, and that I was able to help anyone learn something new.
You can play around with it after achieving this CRUD functionality, for example find out how to display the confirmation message after the user has added a record, or edited/update a record or deleted it. Try adding pagination or a search bar to the main view. If you happen to know jQuery-AJAX, try as much as CRUD functionality using AJAX. Or, at least try giving it a better css 😉
If you have any queries, feedbacks, suggestions etc, feel free to contact me or comment below.
P.S.: You can download the complete CI app folder including the database file from HERE
If you are looking for a reliable team to manage your web development, consider checking out our web development services and pricing page.