PHP codeigniter tuturial
PHP codeigniter tuturial
In the second step, Routing will decide whether to pass this request to step-3 for
caching or to pass this request to step-4 for security check.
If the requested page is already in Caching, then Routing will pass the request to
step-3 and the response will go back to the user.
If the requested page does not exist in Caching, then Routing will pass the
requested page to step-4 for Security checks.
The View will render the page with available data and pass it on for Caching. As
the requested page was not cached before so this time it will be cached in
Caching, to process this page quickly for future requests.
Directory Structure
The image given below shows the directory structure of the CodeIgniter.
CodeIgniter directory structure is divided into 3 folders −
Application
System
User_guide
Application
As the name indicates the Application folder contains all the code of your application that
you are building. This is the folder where you will develop your project. The Application
folder contains several other folders, which are explained below −
Cache − This folder contains all the cached pages of your application. These
cached pages will increase the overall speed of accessing the pages.
Config − This folder contains various files to configure the application. With the
help of config.php file, user can configure the application. Using database.php
file, user can configure the database of the application.
Controllers − This folder holds the controllers of your application. It is the basic
part of your application.
Helpers − In this folder, you can put helper class of your application.
Hooks − The files in this folder provide a means to tap into and modify the inner
workings of the framework without hacking the core files.
Logs − This folder contains files related to the log of the system.
Third_party − In this folder, you can place any plugins, which will be used for
your application.
Views − Application’s HTML files will be placed in this folder.
System
This folder contains CodeIgniter core codes, libraries, helpers and other files, which help
make the coding easy. These libraries and helpers are loaded and used in web app
development.
This folder contains all the CodeIgniter code of consequence, organized into various
folders −
Core − This folder contains CodeIgniter’s core class. Do not modify anything here.
All of your work will take place in the application folder. Even if your intent is to
extend the CodeIgniter core, you have to do it with hooks, and hooks live in the
application folder.
Database − The database folder contains core database drivers and other
database utilities.
Fonts − The fonts folder contains font related information and utilities.
Helpers − The helpers folder contains standard CodeIgniter helpers (such as date,
cookie, and URL helpers).
Language − The language folder contains language files. You can ignore it for
now.
Libraries − The libraries folder contains standard CodeIgniter libraries (to help
you with e-mail, calendars, file uploads, and more). You can create your own
libraries or extend (and even replace) standard ones, but those will be saved in the
application/libraries directory to keep them separate from the standard
CodeIgniter libraries saved in this particular folder.
User_guide
This is your user guide to CodeIgniter. It is basically, the offline version of user guide on
CodeIgniter website. Using this, one can learn the functions of various libraries, helpers
and classes. It is recommended to go through this user guide before building your first
web app in CodeIgniter.
Beside these three folders, there is one more important file named “index.php”. In this
file, we can set the application environment and error level and we can define system and
application folder name. It is recommended, not to edit these settings if you do not have
enough knowledge about what you are going to do.
CodeIgniter - Basic Concepts
Controllers
A controller is a simple class file. As the name suggests, it controls the whole application
by URI.
Creating a Controller
First, go to application/controllers folder. You will find two files there, index.html and
Welcome.php. These files come with the CodeIgniter.
Keep these files as they are. Create a new file under the same path named “Test.php”.
Write the following code in that file −
<?php
class Test extends CI_Controller {
The Test class extends an in-built class called CI_Controller. This class must be
extended whenever you want to make your own Controller class.
Calling a Controller
The above controller can be called by URI as follows −
http://www.your-domain.com/index.php/test
Notice the word “test” in the above URI after index.php. This indicates the class name of
controller. As we have given the name of the controller “Test”, we are writing “test” after
the index.php. The class name must start with uppercase letter but we need to write
lowercase letter when we call that controller by URI. The general syntax for calling the
controller is as follows −
http://www.your-domain.com/index.php/controller/method-name
Creating & Calling Constructor Method
Let us modify the above class and create another method named “hello”.
<?php
class Test extends CI_Controller {
http://www.your-domain.com/index.php/test
http://www.your-domain.com/index.php/test/index
http://www.your-domain.com/index.php/test/hello
After visiting the first URI in the browser, we get the output as shown in the picture given
below. As you can see, we got the output of the method “index”, even though we did not
pass the name of the method the URI. We have used only controller name in the URI. In
such situations, the CodeIgniter calls the default method “index”.
Visiting the second URI in the browser, we get the same output as shown in the above
picture. Here, we have passed method’s name after controller’s name in the URI. As the
name of the method is “index”, we are getting the same output.
Visiting the third URI in the browser, we get the output as shown in picture given below.
As you can see, we are getting the output of the method “hello” because we have passed
“hello” as the method name, after the name of the controller “test” in the URI.
Points to Remember
The name of the controller class must start with an uppercase letter.
Do not use the same name of the method as your parent class, as it will override
parent class’s functionality.
Views
This can be a simple or complex webpage, which can be called by the controller. The
webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us
create a simple view. Create a new file under application/views with name “test.php”
and copy the below given code in that file.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
Where name is the view file, which is being rendered. If you have planned to store the
view file in some directory then you can use the following syntax −
$this->load->view('directory-name/name');
It is not necessary to specify the extension as php, unless something other than .php is
used.
The index() method is calling the view method and passing the “test” as argument to
view() method because we have stored the html coding in “test.php” file under
application/views/test.php.
<?php
class Test extends CI_Controller {
Models
Models classes are designed to work with information in the database. As an example, if
you are using CodeIgniter to manage users in your application then you must have model
class, which contains functions to insert, delete, update and retrieve your users’ data.
<?php
Class Model_name extends CI_Model {
Where Model_name is the name of the model class that you want to give. Each model
class must inherit the CodeIgniter’s CI_Model class. The first letter of the model class
must be in capital letter. Following is the code for users’ model class.
<?php
Class User_model extends CI_Model {
}
?>
The above model class must be saved as User_model.php. The class name and file name
must be same.
Loading Model
Model can be called in controller. Following code can be used to load any model.
$this->load->model('model_name');
Where model_name is the name of the model to be loaded. After loading the model you
can simply call its method as shown below.
$this->model_name->method();
Auto-loading Models
There may be situations where you want some model class throughout your application.
In such situations, it is better if we autoload it.
/*
| ---------------------------------------------------------------
| Auto-Load Models
| ---------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
As shown in the above figure, pass the name of the model in the array that you want to
autoload and it will be autoloaded, while system is in initialization state and is accessible
throughout the application.
Helpers
As the name suggests, it will help you build your system. It is divided into small functions
to serve different functionality. A number of helpers are available in CodeIgniter, which are
listed in the table below. We can build our own helpers too.
Array Helper
1
The Array Helper file contains functions that assist in working with arrays.
CAPTCHA Helper
2 The CAPTCHA Helper file contains functions that assist in creating CAPTCHA
images.
Cookie Helper
3
The Cookie Helper file contains functions that assist in working with cookies.
Date Helper
4
The Date Helper file contains functions that help you work with dates.
5 Directory Helper
The Directory Helper file contains functions that assist in working with
directories.
Download Helper
6
The Download Helper lets you download data to your desktop.
Email Helper
7 The Email Helper provides some assistive functions for working with Email. For a
more robust email solution, see CodeIgniter’s Email Class.
File Helper
8
The File Helper file contains functions that assist in working with files.
Form Helper
9
The Form Helper file contains functions that assist in working with forms.
HTML Helper
10
The HTML Helper file contains functions that assist in working with HTML.
Inflector Helper
11 The Inflector Helper file contains functions that permits you to change words to
plural, singular, camel case, etc.
Language Helper
12 The Language Helper file contains functions that assist in working with language
files.
Number Helper
13
The Number Helper file contains functions that help you work with numeric data.
Path Helper
14 The Path Helper file contains functions that permits you to work with file paths on
the server.
Security Helper
15
The Security Helper file contains security related functions.
16 Smiley Helper
The Smiley Helper file contains functions that let you manage smileys
(emoticons).
String Helper
17
The String Helper file contains functions that assist in working with strings.
Text Helper
18
The Text Helper file contains functions that assist in working with text.
Typography Helper
19 The Typography Helper file contains functions that help your format text in
semantically relevant ways.
URL Helper
20
The URL Helper file contains functions that assist in working with URLs.
XML Helper
21
The XML Helper file contains functions that assist in working with XML data.
Loading a Helper
A helper can be loaded as shown below −
$this->load->helper('name');
Where name is the name of the helper. For example, if you want to load the URL Helper,
then it can be loaded as −
$this->load->helper('url');
Routing
CodeIgniter has user-friendly URI routing system, so that you can easily re-route URL.
Typically, there is a one-to-one relationship between a URL string and its corresponding
controller class/method. The segments in a URI normally follow this pattern −
your-domain.com/class/method/id/
The first segment represents the controller class that should be invoked.
The second segment represents the class function, or method, that should be
called.
The third, and any additional segments, represent the ID and any variables that
will be passed to the controller.
In some situations, you may want to change this default routing mechanism. CodeIgniter
provides facility through which you can set your own routing rules.
$route['default_controller']
This route indicates which controller class should be loaded, if the URI contains
1 no data, which will be the case when people load your root URL. You are
encouraged to have a default route otherwise a 404 page will appear, by default.
We can set home page of website here so it will be loaded by default.
$route['404_override']
This route indicates which controller class should be loaded if the requested
2 controller is not found. It will override the default 404 error page. It won’t affect
to the show_404() function, which will continue loading the default
error_404.php file in application/views/errors/error_404.php.
$route['translate_uri_dashes']
As evident by the Boolean value, this is not exactly a route. This option enables
you to automatically replace dashes (‘-‘) with underscores in the controller and
3
method URI segments, thus saving you additional route entries if you need to do
that. This is required because the dash is not a valid class or method-name
character and will cause a fatal error, if you try to use it.
Wildcards
We can use two wildcard characters as explained below −
(:num) − It will match a segment containing only numbers.
Example
$route['product/:num']='catalog/product_lookup';
In the above example, if the literal word “product” is found in the first segment of the
URL, and a number is found in the second segment, the “catalog” class and the
“product_lookup” method are used instead.
Regular Expressions
Like wildcards, we can also use regular expressions in $route array key part. If any URI
matches with regular expression, then it will be routed to the value part set into $route
array.
Example
$route['products/([a-z]+)/(\d+)']='$1/id_$2';
In the above example, a URI similar to products/shoes/123 would instead call the “shoes”
controller class and the “id_123” method.
CodeIgniter - Cookie Management
Cookie is a small piece of data sent from web server to store on client’s computer.
CodeIgniter has one helper called “Cookie Helper” for cookie management.
In the set_cookie() function, we can pass all the values using two ways. In the first way,
only array can be passed and in the second way, individual parameters can also be
passed.
Example
Create a controller called Cookie_controller.php and save it at
application/controller/Cookie_controller.php
<?php
class Cookie_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('cookie', 'url'));
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
<a href = 'display'>Click Here</a> to view the cookie.<br>
<a href = 'delete'>Click Here</a> to delete the cookie.
</body>
</html>
Change the routes.php file in application/config/routes.php to add route for the above
controller and add the following line at the end of the file.
$route['cookie'] = "Cookie_controller";
$route['cookie/display'] = "Cookie_controller/display_cookie";
$route['cookie/delete'] = "Cookie_controller/deletecookie";
After that, you can execute the following URL in the browser to execute the example.
http://yoursite.com/index.php/cookie
You would like the messages to be displayed, when the application is in developing mode
rather than in production mode as the error messages can be solved easily at the
developing stage.
The environment of your application can be changed, by changing the line given below
from index.php file. This can be set to anything but normally there are three values
(development, test, production) used for this purpose.
show_error() function displays errors in HTML format at the top of the screen.
show_404() function displays error if you are trying to access a page which does
not exist.
Parameters
$page (string) – URI string
log_message() function is used to write log messages. This is useful when you
want to write custom messages.
/*
|--------------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------------
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disable logging, Error logging TURNED OFF
| 1 = Error Message (including PHP errors)
| 2 = Debug Message
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Message, without Error Messages
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
You can find the log messages in application/log/. Make sure that this directory is
writable before you enable log files.
Example
Copy the following code and store it at application/view/Upload_form.php.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
</body>
</html>
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?phpforeach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?phpendforeach; ?>
</ul>
</html>
<?php
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
Make the following change in the route file in application/config/routes.php and add
the following line at the end of file.
$route['upload'] = 'Upload';
Now let us execute this example by visiting the following URL in the browser. Replace the
yoursite.com with your URL.
http://yoursite.com/index.php/upload
After successfully uploading a file, you will see the following screen −
CodeIgniter - Form Validation
Validation is an important process while building web application. It ensures that the data
that we are getting is proper and valid to store or process. CodeIgniter has made this task
very easy. Let us understand this process with a simple example.
Example
Create a view file myform.php and save the below code it in
application/views/myform.php. This page will display form where user can submit his
name and we will validate this page to ensure that it should not be empty while
submitting.
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action = "" method = "">
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Name</h5>
<input type = "text" name = "name" value = "" size = "50" />
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>
</html>
<html>
<head>
<title>My Form</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?php echo anchor('form', 'Try it again!'); ?></p>
</body>
</html>
<?php
if ($this->form_validation->run() == FALSE) {
$this->load->view('myform');
}
else {
$this->load->view('formsuccess');
}
}
}
?>
$route['validation'] = 'Form';
Let us execute this example by visiting the following URL in the browser. This URL may be
different based on your site.
http://yoursite.com/index.php/validation
It will produce the following screen −
We have added a validation in the controller − Name is required field before submitting
the form. So, if you click the submit button without entering anything in the name field,
then you will be asked to enter the name before submitting as shown in the screen below.
After entering the name successfully, you will be redirected to the screen as shown below.
In the above example, we have used the required rule setting. There are many rules
available in the CodeIgniter, which are described below.
Given below are the most commonly used list of native rules available to use.
$this->load->library('class name');
Where class name is the name of the library that we want to load. If we want to load
multiple libraries, then we can simply pass an array as argument to library() function as
shown below −
$this->load->library(array('email', 'table'));
Library Classes
The library classes are located in system/libraries. Each class has various functions to
simplify the developing work. Following table shows the names of the library class and its
description.
Benchmarking Class
1 Benchmarking class is always active, enabling the time difference between any
two marked points to be calculated.
Caching Class
2
This class will cache the pages, to quickly access the page speed.
Calendaring Class
3
Using this class, you can dynamically create calendars.
Config Class
Email Class
6
This class provides email related functionality, like send or reply to email.
Encryption Class
7
This class provides two-way data encryption functionality.
8 This class provides functionalities related to file uploading. You can set various
preferences like type of file to be uploaded, size of the files etc.
FTP Class
10 This class provides various FTP related functions like transferring files to remove
server, moving, renaming or deleting files on server.
Input Class
12
This class pre-processes the input data for security reason.
Language Class
13
This class is used for internationalization.
Loader Class
14
This class loads elements like View files, Drivers, Helpers, Models etc.
15 Migrations Class
This class provides functionalities related to database migrations.
Output Class
16
This class sends the output to browser and also, caches that webpage.
Pagination Class
17
This class adds pagination functionalities to web page.
The Template Parser Class can perform simple text substitution for pseudo-
18
variables contained within your view files. It can parse simple variables or
variable tag pairs.
Security Class
19
This class contains security related functions like XSS Filtering, CSRF etc.
Session Library
20
This class provides functionalities to maintain session of your application.
HTML Table
21
This class is used to auto-generate HTML tables from array or database results.
Trackback Class
22 The Trackback Class provides functions that enable you to send and receive
Trackback data.
Typography Class
23
The Typography Class provides methods that help to format text.
24 This class provides functionalities to unit test your application and generate the
result.
URI Class
The URI Class provides methods that help you retrieve information from your URI
25
strings. If you use URI routing, you can also retrieve information about the
rerouted segments.
User Agent Class
The User Agent Class provides functions that help identify information about the
26 browser, mobile device, or robot visiting your site. In addition, you can get
referrer information as well as language and supported character-set
information.
Creating Libraries
CodeIgniter has rich set of libraries, which you can find in system/libraries folder but
CodeIgniter is not just limited to system libraries, you can create your own libraries too,
which can be stored in application/libraries folder. You can create libraries in three
ways.
The name of the file must start with a capital letter e.g. Mylibrary.php
The class name must start with a capital letter e.g. class Mylibrary
The name of the class and name of the file must match.
Mylibrary.php
class Mylibrary {
The above library can be loaded by simply executing the following line in your controller.
$this->load->library(‘mylibrary’);
mylibrary is the name of your library and you can write it in lowercase as well as
uppercase letters. Use the name of the library without “.php” extension. After loading the
library, you can also call the function of that class as shown below.
$this->mylibrary->some_function();
Here, in the above example, MY_Email class is extending the native library’s email class
CI_Email. This library can be loaded by the standard way of loading email library. Save the
above code in file My_Email.php
Email.php
Class CI_Email {
}
CodeIgniter - MVC Framework
CodeIgniter is based on the Model-View-Controller (MVC) development pattern.
MVC is a software approach that separates application logic from presentation. In practice,
it permits your web pages to contain minimal scripting since the presentation is separate
from the PHP scripting.
The Model represents your data structures. Typically, your model classes will
contain functions that help you retrieve, insert and update information in your
database.
The View is information that is being presented to a user. A View will normally be
a web page, but in CodeIgniter, a view can also be a page fragment like a header
or footer. It can also be an RSS page, or any other type of “page”.
The Controller serves as an intermediary between the Model, the View, and any
other resources needed to process the HTTP request and generate a web page.
CodeIgniter - Sending Email
Sending email in CodeIgniter is much easier. You also configure the preferences regarding
email in CodeIgniter. CodeIgniter provides following features for sending emails −
Multiple recipients
CC and BCCs
Attachments
Word wrapping
Priorities
BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
Email class has the following functions to simplify the job of sending emails.
Return
S.N. Syntax Parameters Return
Type
CI_Email
$to (mixed) − Comma-
instance
2 to($to) delimited string or an array of CI_Email
(method
e-mail addresses
chaining)
CI_Email
$subject (string) − E-mail instance
5 subject($subject) CI_Email
subject line (method
chaining)
CI_Email
$body (string) − E-mail instance
6 message($body) CI_Email
message body (method
chaining)
CI_Email
$str (string) − Alternative e- instance
7 set_alt_message($str) CI_Email
mail message body (method
chaining)
CI_Email
$clear_attachments (bool)
clear([$clear_attachments = instance
9 – Whether or not to clear CI_Email
FALSE]) (method
attachments
chaining)
CI_Email
$auto_clear (bool) −
instance
10 send([$auto_clear = TRUE]) Whether to clear message CI_Email
(method
data automatically
chaining)
Attachment
$filename (string) − Existing Content-ID
12 attachment_cid($filename) string
attachment filename or FALSE if
not found
Sending an Email
To send an email using CodeIgniter, first you have to load email library using the following
−
$this->load->library('email');
After loading the library, simply execute the following functions to set necessary elements
to send an email. The from() function is used to set − from where the email is being sent
and to() function is used − to whom the email is being sent. The subject() and
message() function is used to set the subject and message of the email.
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
After that, execute the send() function as shown below to send an email.
$this->email->send();
Example
Create a controller file Email_controller.php and save it in
application/controller/Email_controller.php.
<?php
class Email_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
}
$this->load->helper('form');
$this->load->view('email_form');
}
//Send mail
if($this->email->send())
$this->session->set_flashdata("email_sent","Email sent successfully.");
else
$this->session->set_flashdata("email_sent","Error in sending Email.");
$this->load->view('email_form');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Email Example</title>
</head>
<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Email_controller/send_mail');
?>
<?php
echo form_close();
?>
</body>
</html>
Make the changes in the routes.php file in application/config/routes.php and add the
following line at the end of the file.
$route['email'] = 'Email_Controller';
Execute the above example by visiting the following link. Replace the yoursite.com with
the URL of your site.
http://yoursite.com/index.php/email
CodeIgniter - Session Management
When building websites, we often need to track user’s activity and state and for this
purpose, we have to use session. CodeIgniter has session class for this purpose.
Initializing a Session
Sessions data are available globally through the site but to use those data we first need to
initialize the session. We can do that by executing the following line in constructor.
$this->load->library('session');
After loading the session library, you can simply use the session object as shown below.
$this->session
$_SESSION[‘key’] = value;
Where ‘key’ is the key of array and value is assigned on right side of equal to sign.
$this->session->set_userdata('some_name', 'some_value');
set_userdata() function takes two arguments. The first argument, some_name, is the
name of the session variable, under which, some_value will be stored.
set_userdata() function also supports another syntax in which you can pass array to
store values as shown below.
$newdata = array(
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
unset($_SESSION[‘some_name’]);
Removing session data in CodeIgniter is very simple as shown below. The below version of
unset_userdata() function will remove only one variable from session.
$this->session->unset_userdata('some_name');
If you want to remove more values from session or to remove an entire array you can use
the below version of unset_userdata() function.
$this->session->unset_userdata($array_items);
$name = $this->session->userdata('name');
Example
Create a controller class called Session_controller.php and save it in
application/controller/Session_controller.php.
<?php
class Session_controller extends CI_Controller {
$this->load->view('session_view');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Session Example</title>
</head>
<body>
Welcome <?php echo $this->session->userdata('name'); ?>
<br>
<a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/
Click Here</a> to unset session data.
</body>
</html>
Make the changes in the routes.php file in application/config/routes.php and add the
following line at the end of the file.
$route['sessionex'] = 'Session_Controller';
Execute the above example by using the following address. Replace yoursite.com with
the URL of your site.
http://yoursite.com/index.php/sessionex
CodeIgniter - Working with Database
Like any other framework, we need to interact with the database very often and
CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact
with database.
In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions
work with CodeIgniter. We will use stud table to select, update, delete, and insert the
data in stud table.
roll_no int(11)
name varchar(30)
Connecting to a Database
We can connect to database in the following two way −
$autoload['libraries'] = array(‘database’);
Manual Connecting − If you want database connectivity for only some of the
pages, then we can go for manual connecting. We can connect to database
manually by adding the following line in any class.
$this->load->database();
Here, we are not passing any argument because everything is set in the database config
file application/config/database.php
Inserting a Record
To insert a record in the database, the insert() function is used as shown in the following
table −
Syntax insert([$table = ''[, $set = NULL[, $escape = NULL]]])
The following example shows how to insert a record in stud table. The $data is an array in
which we have set the data and to insert this data to the table stud, we just need to pass
this array to the insert function in the 2nd argument.
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->insert("stud", $data);
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Updating a Record
To update a record in the database, the update() function is used along with set() and
where() functions as shown in the tables below. The set() function will set the data to be
updated.
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->set($data);
$this->db->where("roll_no", ‘1’);
$this->db->update("stud", $data);
Deleting a Record
To delete a record in the database, the delete() function is used as shown in the following
table −
Use the following code to to delete a record in the stud table. The first argument indicates
the name of the table to delete record and the second argument decides which record to
delete.
Selecting a Record
To select a record in the database, the get function is used, as shown in the following
table −
$query = $this->db->get("stud");
$data['records'] = $query->result();
Closing a Connection
Database connection can be closed manually, by executing the following code −
$this->db->close();
Example
Create a controller class called Stud_controller.php and save it at
application/controller/Stud_controller.php
<?php
class Stud_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
$this->load->helper('url');
$this->load->view('Stud_view',$data);
}
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}
?>
<?php
class Stud_Model extends CI_Model {
function __construct() {
parent::__construct();
}
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<?php
echo form_open('Stud_controller/add_student');
echo form_label('Roll No.');
echo form_input(array('id'=>'roll_no','name'=>'roll_no'));
echo "<br/>";
echo form_label('Name');
echo form_input(array('id'=>'name','name'=>'name'));
echo "<br/>";
echo form_submit(array('id'=>'submit','value'=>'Add'));
echo form_close();
?>
</body>
</html>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<form method = "" action = "">
<?php
echo form_open('Stud_controller/update_student');
echo form_hidden('old_roll_no',$old_roll_no);
echo form_label('Roll No.');
echo form_input(array('id'⇒'roll_no',
'name'⇒'roll_no','value'⇒$records[0]→roll_no));
echo "
";
echo form_label('Name');
echo form_input(array('id'⇒'name','name'⇒'name',
'value'⇒$records[0]→name));
echo "
";
</form>
</body>
</html>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<a href = "<?php echo base_url(); ?>
index.php/stud/add_view">Add</a>
</body>
</html>
Make the following change in the route file at application/config/routes.php and add
the following line at the end of file.
$route['stud'] = "Stud_controller";
$route['stud/add'] = 'Stud_controller/add_student';
$route['stud/add_view'] = 'Stud_controller/add_student_view';
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1';
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';
Now, let us execute this example by visiting the following URL in the browser. Replace the
yoursite.com with your URL.
http://yoursite.com/index.php/stud