0% found this document useful (0 votes)
211 views91 pages

The Working of Codeigniter Application Is Mentioned in A Simple Flowchart Given Below

CodeIgniter is an MVC framework that separates application logic from presentation. It has easy installation steps and a simple directory structure. The main directories are Application, System, and User_Guide. Application contains controllers, models, views, and other application code. System contains core framework files. Controllers serve as intermediaries between models and views. Views generate the UI without logic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
211 views91 pages

The Working of Codeigniter Application Is Mentioned in A Simple Flowchart Given Below

CodeIgniter is an MVC framework that separates application logic from presentation. It has easy installation steps and a simple directory structure. The main directories are Application, System, and User_Guide. Application contains controllers, models, views, and other application code. System contains core framework files. Controllers serve as intermediaries between models and views. Views generate the UI without logic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CodeIgniter Installation

Codeigniter installation is a very easy process. For the installation please follow the
given below steps:

• Step 1 : Click at the link to download the


Codingniter:[Link]
o Codeigniter comes in three flavors: CodeIgniter 3 (Current), CodeIgniter
4 (Future) and CodeIgniter 2 (Legacy). For more details follow the link
mentioned above.
o We can also get all the latest scripts with GitHub.
• Step 2 : Unzip the folder
• Step 3 :Upload all the files and folders to your server.
• Step 4 :After following step 3, visit the URL of your server, e.g. [Link]–
[Link]
On visiting the URL you will see the given below type of screen.

So here is 3rd chapter of the Codeigniter tutorial, click on next Page

CodeIgniter Application Architecture


The working of Codeigniter Application is mentioned in a simple flowchart given below,
which will help you understand the entire process effortlessly in easy steps. Each and every
step in the flow chart is explained in elaboration and point wise for your easy grasping.
• As shown in the Flow chart, whenever a request comes to CodeIgniter, it will
first go to [Link] page.
• In the second step, Routing decides whether to pass the request to step 3
for Caching or to pass the request to step 4 for Security check.
• If the requested page is already in Caching, then Routing will sanction the
request to step 3 and the response will go back to the user.
• In case the request page does not exist in the Caching, then Routing, will
sanction the requested page to step 4 for Security checks.
• Before passing the request to Application Controller, the Security of the
submitted data is checked. After the Security check is done, the Application
Controller loads all the necessary Models, Libraries, Helpers,
Plugins and Scripts and pass it onto View.
• The View will provide the page with available data and pass that on
for Caching, to process this page quickly for future requests.

Directory Structure of Codeigniter


The Directory structure of the Codeigniter is given below in the Screenshot Image:

A comprehensive power portfolio


Further to this the Directory Structure of CodeIgniter is divided into three folders:

• Application
• System

• User_Guide

Application
As indicated in the name the Application folder contains all the code of your
application that you are building. This folder is the actual place where we develop the
project. Within this application folder there exist several other folders as explained
below:

• Cache - The Cache folder contains all the cached pages of your application. These
cached pages would increase the overall speed of accessing the pages.

• Config - The Config folder contains various files to configure the application. With the
help of [Link] file, you can configure the application. Using [Link] file, you
can configure the database of your application.

• Controllers – This folder contains the controllers of your application. It is the basic
part of your application.
• Core - This folder contains the base class of your application.

• Helpers – The helper class of your application can be put in this folder.

• Hooks – With the help of files in this folder you can tap into and modify the inner
workings of the framework without hacking the core files.
• Libraries – This folder contains the files of the library developed for your application.

• Logs – This folder contains the files related to the log of the system.
• Language –This folder contains language related files.

• Models – The database login is placed in this file.

• Third_Party – The plugins can be placed in this folder for using it in your application.

• Views – The HTML files of your application can be placed here.

System:
The System folder contains the CodeIgniter core codes, libraries, helpers and other
files, which helps make the coding easy. The libraries and helpers are loaded and
used for web application development. This folder contains all the CodeIgniter code
of consequence again organized into various folders mentioned as below:

• Core – The Core folder contains CodeIgniter core class. Nothing should be
modified here. Since all your work will take place in the application folder, if
you intend you extend the CodeIgniter core you will have to do it with
hooks, which itself exist in the application folder.
• Database – This folder contains the database drivers and database utilities.
• Fonts – This folder contains the font related information and the utilities.
• Helpers – The standard CodeIgniter helpers such as data, cookie, and URL
helpers exist in this folder.
• Language –Contains language related files. This can be ignored for now.
• Libraries – The folder contains standard CodeIgniter libraries such as e-
mail, calendars, file uploads etc. You can create your own libraries, 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 in this particular folder.
User_Guide:
It is the offline version of user guide of CodeIgniter Website. In other words
user guide to CodeIgniter. Using this the various functions of libraries,
classes and helpers can be learned. It is highly recommended that you go
through this user guide before building your first web app using CodeIgniter.
Apart from these three folders ( Application, System and User_Guide ) there
is one more important file named “ [Link]” . In this file you can set the
application environment and error level and you can define system and
application folder name. We highly recommend you not to edit these
settings if you do not have enough knowledge of what you are going to do.

A comprehensive power portfolio

CodeIgniter - MVC Framework


Codeigniter is PHP Framework which is built on the top of the MVC (Model-View-
Controller) development pattern. Model-View-Controller is a software approach
which separates application logic from presentation. Since the presentation is
separate from the PHP scripting here, it permits the web pages to contain minimal
scripting.

• Model- The Model consists of the data structures. In a way These


typically contains the sets of the functions that helps in retrieving,
inserting and updating information in the database.
• View- The view is the information that is being presented to the user.
A view in normal case is a webpage, but in case of Codeigniter, it can
be a page fragment like header or footer, or it can be any other type
of page like RSS as well as for performing UI.
• Controller- The controller implements the logical implementation for
writing the programme and creating the webpage. The controller
serves as an intermediary between the model and the view and any
other resources needed to process HTTP request and generate a
webpage.

Codeigniter controller

Motor Control Solutions

Controller
The controller implements the logical implementation for writing the
programme and creating the webpage. The controller serves as an
intermediary between the model and the view. The Controller Controls
Model as well as view.

Creating a Controller
Controller always stored inside Application/controllers folder. Condeigniter
provides two basic files that is stored
inside Application/controllers folder [Link] and [Link].
Keep these files as they are don't delete these files. Now Create a new file
under the same path(Application/controllers) named "[Link]"

<?php
class Hello extends CI_Controller
{
public function index()
{
echo "Hello World";
}
}
?>
Save Hello class inside Application/controllers/[Link]. Here, Hello class inherit
an in-built Codeigniter Class CI_Controller.

Points to Remember
Calling a Controller
• CI_Controller class must be extended Whenever u want to create Your own
Controller.
• Controller name must be Started with Capital letter
• Controller name and file name must be Similar
• Syntax

• [Link]

Open Your Web browser and type inside


"[Link] OR "[Link]
deIgniter/[Link]/Hello/index"

Explanation: Here Hello is Controller name and index is method


name. By default index method automatically calls so if u want to call
then type inside url otherwise leave method name.

Output

Creating Hello Controller with 2 methods index and


about
<?php
class Hello extends CI_Controller
{
public function index()
{
echo "Hello World";
}
public function about()
{
echo "About us";
}
}
?>

Calling Hello Controller's index method


[Link]

Output Hello World


Calling Hello Controller's about method
[Link]

Output About us

Codeigniter Views

Views
The view is a simple webpage(designing page) which called by Controller.

The view(designing page) can't access directly it always called


by Controller.

Lets create a simple view page and call on a Controller's method. Ex

<!DOCTYPE html>
<html>
<head>
<title>About CI View</title>
</head>

<body>
<h1>About Codeigniter Views</h1>
</body>
</html>

Save this file inside Application/views/[Link].

loading view on a controller


The view can be loaded on a controller following syntax :

$this->load->view('view_page_name');

Sometimes we can create different directly like user, admin etc. inside user
directory we may store header, footer,sidebar for users same as admin
inside admin directory, in this case we can call like :
$this->load->view('directory_name/view_page_name');

Calling view on a Controller


Add a new mehtod about()
on Hello Controller Application/controllers/[Link].

<?php
class Hello extends CI_Controller
{
public function index()
{
echo "Hello World";
}
public function about()
{
$this->load->view('about');
}

}
?>

Here Hello Controller has now 2 methods. One is index() that contains
"Hello World" message only. Second method about() is calling [Link]
view page. Note : inside Controller no need to call page extension of view.

Calling about() method of Hello Controller


[Link]

Codeigniter Models

Models
Models are the classes designed to work with information in the database.
For example, if we are using CodeIgniter to manage users in our application
then we must have model class, which contains functions to insert, update,
display and delete data.

Creating Model Class

<?php
class Model_name extends CI_Model
{
public function __construct()
{
parent::__construct();
}
}
?>

Note : Model Classes always stored inside Applicaion/models directory. Model


Class name must be started with Capital Letters(or use camel case). Class name
and Page name must be similar. Each Model class inherit Codeigniter's CI_Model
Class .

Create a user's Model Class


<?php
class UserModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
}
?>

Here we have created a model class UserModel. UserModel Class must be


saved inside Application/modesl/[Link]

Loading Model
Every Model class called/used inside a Controller. To call a model class
inside controller following code can be used

$this->load->model('model_name');

After loading model class inside Controller we can use other methods of
Model Class Syntax

$this->model_name->method_name();

codeigniter insert data database


CodeIgniter Insert Data into Database
In this tutorial, We will understand how to insert data into database using
Controller model and view. We will use users table
to insert, display, update and delete.

Table Name : users


user_id int primary key auto_increment
name char(50)
email varchar(100)
mobile bigint

Connecting to a Database
In CodeIgniter, We can connect with database in 2 ways. [Link]
Connecting - Automatic Connection can be done
using application/config/[Link]

$autoload['libraries'] = array('database');

2. Manual Connecting - If u want database connection for some specific


Controller then u can use Manual Connection. in manual Connection u will
have to Create connection for every Controller So it would be better to
use Automatic Connection.

$this->load->database();

Creating a Controller
Create a new file under the path Application/controllers/[Link] Copy
the below given code in your controllers.

<?php
class Hello extends CI_Controller
{
public function __construct()
{
//call CodeIgniter's default Constructor
parent::__construct();

//load database libray manually


$this->load->database();

//load Model
$this->load->model('Hello_Model');
}
public function savedata()
{
//load registration view form
$this->load->view('registration');

//Check submit button


if($this->input->post('save'))
{
//get form's data and store in local varable
$n=$this->input->post('name');
$e=$this->input->post('email');
$m=$this->input->post('mobile');

//call saverecords method of Hello_Model and pass variables as parameter


$this->Hello_Model->saverecords($n,$e,$m);
echo "Records Saved Successfully";
}
}
}
?>

Creating a View
Create a new file under the path Application/views/[Link] Copy the below given
code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
</head>

<body>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">Enter Your Name </td>
<td width="329"><input type="text" name="name"/></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="save"
value="Save Data"/></td>
</tr>
</table>
</form>
</body>
</html>

Creating a Model
Create a new file under the path Application/models/Hello_Model.php Copy the below
given code in your model.

<?php
class Hello_Model extends CI_Model
{
function saverecords($name,$email,$mobile)
{
$query="insert into users values('','$name','$email','$mobile')";
$this->db->query($query);
}
}

Calling/run Hello Controller’s savedata method


Open your web browser and Pass : [Link]

Output : View Page

Output : Database
Codeigniter display data from database

Codeigniter display data from database


In this tutorial, we will understand how to display(fetch) data from
database and display records in view. In the Previous example we saved
records inside users table.
In this example We will use users table to display records.

Controller
Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('Hello_Model');
}

public function savedata()


{
$this->load->view('registration');
if($this->input->post('save'))
{
$n=$this->input->post('name');
$e=$this->input->post('email');
$m=$this->input->post('mobile');
$this->Hello_Model->saverecords($n,$e,$m);
redirect("Hello/dispdata");
}
}

public function dispdata()


{
$result['data']=$this->Hello_Model->displayrecords();
$this->load->view('display_records',$result);
}
}
?>

View
Copy the below given code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Display Records</title>
</head>

<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr style="background:#CCC">
<th>Sr No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
</tr>
<?php
$i=1;
foreach($data as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->name."</td>";
echo "<td>".$row->email."</td>";
echo "<td>".$row->mobile."</td>";
echo "</tr>";
$i++;
}
?>
</table>

</body>
</html>
Model
Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model
{
function saverecords($name,$email,$mobile)
{
$query="insert into users values('','$name','$email','$mobile')";
$this->db->query($query);
}

function displayrecords()
{
$query=$this->db->query("select * from users");
return $query->result();
}
}

Calling/run Hello Controller’s dispdata method


Open your web browser and Pass
: [Link]

Home >>Codeigniter Tutorial >Codeigniter delete database record


Codeigniter delete database record

Codeigniter delete database record


In this tutorial, we will understand how to delete data from database. We will
use users table to delete records.

Controller
Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('Hello_Model');
}
public function savedata()
{
$this->load->view('registration');
if($this->input->post('save'))
{
$n=$this->input->post('name');
$e=$this->input->post('email');
$m=$this->input->post('mobile');
$this->Hello_Model->saverecords($n,$e,$m);
redirect("Hello/dispdata");
}
}

public function dispdata()


{
$result['data']=$this->Hello_Model->displayrecords();
$this->load->view('display_records',$result);
}

public function deletedata()


{
$id=$this->input->get('id');
$this->Hello_Model->deleterecords($id);
redirect("Hello/dispdata");
}
}
?>

View
Copy the below given code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Display Records</title>
</head>

<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr style="background:#CCC">
<th>Sr No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Delete</th>
</tr>
<?php
$i=1;
foreach($data as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->name."</td>";
echo "<td>".$row->email."</td>";
echo "<td>".$row->mobile."</td>";
echo "<td><a href='deletedata?id=".$row->user_id."'>Delete</a></td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>

Model
Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model
{
function saverecords($name,$email,$mobile)
{
$query="insert into users values('','$name','$email','$mobile')";
$this->db->query($query);
}

function displayrecords()
{
$query=$this->db->query("select * from users");
return $query->result();
}

function deleterecords($id)
{
$this->db->query("delete from users where user_id='".$id."'");
}
}
?>

Calling/run Hello Controller’s dispdata method


Open your web browser and Pass : [Link]

Output
Codeigniter update database record

Codeigniter update database record


In this tutorial, we will understand how to Update records. We will use users table to update records.

Controller
Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('Hello_Model');
}

public function savedata()


{
$this->load->view('registration');
if($this->input->post('save'))
{
$n=$this->input->post('name');
$e=$this->input->post('email');
$m=$this->input->post('mobile');
$this->Hello_Model->saverecords($n,$e,$m);
redirect("Hello/dispdata");
}
}

public function dispdata()


{
$result['data']=$this->Hello_Model->displayrecords();
$this->load->view('display_records',$result);
}

public function deletedata()


{
$id=$this->input->get('id');
$this->Hello_Model->deleterecords($id);
redirect("Hello/dispdata");
}

public function updatedata()


{
$id=$this->input->get('id');
$result['data']=$this->Hello_Model->displayrecordsById($id);
$this->load->view('update_records',$result);
if($this->input->post('update'))
{
$n=$this->input->post('name');
$e=$this->input->post('email');
$m=$this->input->post('mobile');
$this->Hello_Model->updaterecords($n,$e,$m,$id);
redirect("Hello/dispdata");
}
}
}
?>

Display Records View


Copy the below given code in your display_records.php View Page.

<!DOCTYPE html>
<html>
<head>
<title>Display Records</title>
</head>

<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr style="background:#CCC">
<th>Sr No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
$i=1;
foreach($data as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->name."</td>";
echo "<td>".$row->email."</td>";
echo "<td>".$row->mobile."</td>";
echo "<td><a href='deletedata?id=".$row->user_id."'>Delete</a></td>";
echo "<td><a href='updatedata?id=".$row->user_id."'>Update</a></td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>

Update Records View


Copy the below given code in your update_records.php View Page.

<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
</head>

<body>
<?php
$i=1;
foreach($data as $row)
{
?>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">Enter Your Name </td>
<td width="329"><input type="text" name="name" value="<?php echo $row-
>name; ?>"/></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email" value="<?php echo $row->email;
?>"/></td>
</tr>
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile" value="<?php echo $row->mobile;
?>"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="update" value="Update Records"/></td>
</tr>
</table>
</form>
<?php } ?>
</body>
</html>

Model
Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model
{
function saverecords($name,$email,$mobile)
{
$query="insert into users values('','$name','$email','$mobile')";
$this->db->query($query);
}
function displayrecords()
{
$query=$this->db->query("select * from users");
return $query->result();
}

function deleterecords($id)
{
$this->db->query("delete from users where user_id='".$id."'");
}

function displayrecordsById($id)
{
$query=$this->db->query("select * from users where
user_id='".$id."'");
return $query->result();
}

function updaterecords($name,$email,$mobile,$id)
{
$query=$this->db->query("update users SET
name='$name',email='$email',mobile='$mobile' where user_id='".$id."'");
}
}
?>

Calling/run Hello Controller’s dispdata method


Open your web browser and Pass : [Link]

Output(Display Records)

Output(Update Records)
Create registration form in codeigniter

Create registration form in codeigniter


In this tutorial we will understand how to create simple registration form in CodeIgniter.
Before inserting Students data inside database we will check student email id is already exists
then show error message "User already exists" if not already exists then store information
inside database. We will use student table to save data. This is student table structure

Table Name : student

student_id int primary key auto_increment

name char(50)

email varchar(100)

password varchar(100)

mobile bigint

course char(100)

Controller
Copy the below given code in your User Controller. In this example we have not used proper
model page , all database query wrote in Controller.

<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}

public function index()


{

if($this->input->post('register'))
{
$n=$this->input->post('name');
$e=$this->input->post('email');
$p=$this->input->post('pass');
$m=$this->input->post('mobile');
$c=$this->input->post('course');

$que=$this->db->query("select * from student where


email='".$e."'");
$row = $que->num_rows();
if($row)
{
$data['error']="<h3 style='color:red'>This user already
exists</h3>";
}
else
{
$que=$this->db->query("insert into student
values('','$n','$e','$p','$m','$c')");

$data['error']="<h3 style='color:blue'>Your account created


successfully</h3>";
}

}
$this->load->view('student_registration',@$data);
}
}
?>

Registration View
Copy the below given code in your student_registration.php View Page.

<!DOCTYPE html>
<html>
<head>
<title>Student Registration form</title>
</head>

<body>
<form method="post">
<table width="600" align="center" border="1" cellspacing="5"
cellpadding="5">
<tr>
<td colspan="2"><?php echo @$error; ?></td>
</tr>
<tr>
<td width="230">Enter Your Name </td>
<td width="329"><input type="text" name="name"/></td>
</tr>

<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email"/></td>
</tr>

<tr>
<td>Enter Your Password </td>
<td><input type="password" name="pass"/></td>
</tr>

<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>

<tr>
<td>Select Your Course </td>
<td>
<select name="course">
<option value="">Select Course</option>
<option>PHP</option>
<option>Java</option>
<option>Wordpress</option>
</select>
</td>
</tr>

<tr>
<td colspan="2" align="center">
<input type="submit" name="register" value="Register Me"/></td>
</tr>
</table>

</form>
</body>
</html>

Execute User Controller’s index method


Open your web browser and Pass : [Link]

Output(Save Records if email id is not already exists)


Output(Show error "This user already exists")

Create login form in Codeigniter

Create login form in Codeigniter


In this tutorial we will understand how to create simple login form in CodeIgniter. For login page we
will check student's email and password is valid then redirect on dashboard method. otherwise
display an error message on login view page. We will use student table to login This is student table
structure

Table Name : student

student_id int primary key auto_increment


name char(50)

email varchar(100)

password varchar(100)

mobile bigint

course char(100)

Controller
Copy the below given code in your User Controller.

<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}

public function login()


{

if($this->input->post('login'))
{
$e=$this->input->post('email');
$p=$this->input->post('pass');

$que=$this->db->query("select * from student where


email='".$e."' and password='$p'");
$row = $que->num_rows();
if($row)
{
redirect('User/dashboard');
}
else
{
$data['error']="<h3 style='color:red'>Invalid login
details</h3>";
}
}
$this->load->view('login',@$data);
}

function dashboard()
{
$this->load->view('dashboard');
}
}
?>
Login View
Copy the below given code in your [Link] View Page.

<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
</head>

<body>
<form method="post">
<table width="600" align="center" border="1" cellspacing="5" cellpadding="5">
<tr>
<td colspan="2"><?php echo @$error; ?></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email"/></td>
</tr>

<tr>
<td width="230">Enter Your Password </td>
<td width="329"><input type="password" name="pass"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="login" value="Login"/></td>
</tr>
</table>

</form>
</body>
</html>

Execute User Controller’s login method


Open your web browser and Pass : [Link]

Output(if wrong email or Password)


Dashboard View
Copy the below given code in your [Link] View Page.

<!DOCTYPE html>
<html>
<head>
<title>Student Dashboard</title>
</head>

<body>
<h1>Welcome to your dashboard...</h1>
</body>
</html>

Output(Dashboard page)

CodeIgniter Insert Data into Database

CodeIgniter Insert Data into Database


CodeIgniter gives you access to a Query Builder class. This pattern allows information to be retrieved,
inserted, and updated in your database with minimal scripting. In some cases only one or two lines of
code are necessary to perform a database action. In this tutorial we will understand how to Save
Records inside database using CodeIgniter Core Library. Here we are going to use student table to
Save Records and Check user's existence. This is student table structure

Table Name : student

student_id int primary key auto_increment

name char(50)

email varchar(100)

password varchar(100)

mobile bigint
course char(100)

Controller
Copy the below given code in your User Controller.

<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}

public function index()


{
if($this->input->post('register'))
{
//first check user's email id already exists or not
$query=$this->db->get_where("student",array('email'=>$this->input-
>post('email')));

//count number of matching rows


$row=$query->num_rows();

if($row)
{
$data['error']="<h3 style='color:red'>This user already
exists</h3>";
}
else
{
$data=array('student_id'=>'',
'name'=>$this->input->post('name'),
'email'=>$this->input->post('email'),
'password'=>$this->input-
>post('pass'),
'mobile'=>$this->input-
>post('mobile'),
'course'=>$this->input-
>post('course'));

$this->db->insert('student',$data);

$data['error']="<h3 style='color:blue'>Your account created


successfully</h3>";
}

}
$this->load->view('student_registration',@$data);
}

}
?>

Registration View
<!DOCTYPE html>
<html>
<head>
<title>Student Registration form</title>
</head>

<body>
<form method="post">
<table width="600" align="center" border="1" cellspacing="5"
cellpadding="5">
<tr>
<td colspan="2"><?php echo @$error; ?></td>
</tr>
<tr>
<td width="230">Enter Your Name </td>
<td width="329"><input type="text" name="name"/></td>
</tr>

<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email"/></td>
</tr>

<tr>
<td>Enter Your Password </td>
<td><input type="password" name="pass"/></td>
</tr>

<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>

<tr>
<td>Select Your Course </td>
<td>
<select name="course">
<option value="">Select Course</option>
<option>PHP</option>
<option>Java</option>
<option>Wordpress</option>
</select>
</td>
</tr>

<tr>
<td colspan="2" align="center">
<input type="submit" name="register" value="Register Me"/></td>
</tr>
</table>
</form>
</body>
</html>

Execute User Controller’s index method


Open your web browser and Pass : [Link]

Output(Save Records if email id is not already exists)

Output(Show error "This user already exists")

How to Upload image in codeigniter


How to Upload file & image in codeigniter
There are 3 Steps to Upload image in Codeigniter.
Step 1 :Folder Creation
First We need to Create a folder which form the basis of the upload
process.

This folder is the destination folder where image will store after Uploading .

Go to the root of the CI installation -> Create a folder named "upload". All
Imags will Store inside "Upload " Folder.

Step 2 :Create Controller


Second Step is Create a controller file and save inside Controller folder.
Name of the Controller is "ImageUpload_Controller.php".

In this Controller, firstl I will load two "library" and Second I will load
a "Form helper" class, with the following code.

$this->load->library('form_validation');
$this->load->library(‘upload’);
$this->load->helper('url', 'form');

Add the following Code in controller (ImageUpload_Controller.php)

<?php
class ImageUpload_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
//load Helper for Form
$this->load->helper('url', 'form');
$this->load->library('form_validation');
}
function index()
{
$this->load->view('imageupload_form');
}
public function upload()
{
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2000;
$config['max_width'] = 1500;
$config['max_height'] = 1500;

$this->load->library('upload', $config);

if (!$this->upload->do_upload('profile_pic'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageupload_form', $error);
}
else
{
$data = array('image_metadata' => $this->upload->data());

$this->load->view('imageupload_success', $data);
}
}

}
?>

Step 3 :View
For the Structure of image upload, I have created two files that is stored
inside Ci root view folder.

First file is to upload image and Second file is display Success message.

Structure of "imageupload_form.php" this for uploading a image.

<!DOCTYPE html>
<html>
<head>
<title>Upload Image in Codeigniter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php echo @$error; ?>
<?php echo form_open_multipart('ImageUpload_Controller/upload');?>
<?php echo "<input type='file' name='profile_pic' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</body>
</body>
</html>

Success Message View

<!DOCTYPE html>
<html>
<head>
<title>Image Uploaded Success</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Congreates image uploaded successfully</h1>
</body>
</html>
Output

After Uploading Check image

How to Remove [Link] in Codeigniter


In CodeIgniter URLs are designed to be search engine and human friendly By
default.
In Codeigniter by default [Link] is included in the URLs. But We can easily
remove the [Link] from Codeigniter URLs using .htacss file.

Default Codegniter URLs look like this

[Link]

Why we should remove [Link] from Codeginiter


URLs ?
All we know Codeigniter URLs are designed Search Engine Friendly as well
as User Friendly By default. So we also want to maintain the standard of
URLs, thats why we always remove [Link] from Codeigniter URLs.
To remove [Link] from URLs we have to follow
Some Steps.
Step 1 First we need to update our [Link] file(Line no 38).

Open application/config/[Link] file.

//old Code
$config['index_page'] = "[Link]”
//New updated code(Onlye Need to remove [Link] )
$config['index_page'] = ""

Step 2 We need to create .htaccess file and save inside Codeigniters Root

Add these few lines inside .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ [Link]/$1 [L]

Output
How to use pagination in codeigniter
Pagination in Codeigniter with Step by Step
Example
Pagination basically implies the client can navigate the pages of results,
seeing a subset of them each time, as opposed to looking down the screen
for a very long time.

Pagination is especially valuable when you are coding an application that


interfaces with a database.

In this tutorial, I will use CodeIgniter's pagination library to demonstrate to


you how you can make a paginated rundown of results from a MySQL
database.

Given below topic we will cover in this tutorial,

1. Database Configuration
2. Pagination Controller
3. Pagination Library
4. Pagination Model

Database Configuration
First of all we have to create a database and Store some dummy Records
inside the table. Inside a Single table we are going to store minumum 50
Records, and will display on View 10 Records on every page.

CREATE TABLE `student` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`course` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
)

Once created table insert 50 records in student table(Here email id is not


unique so we can add multiple same email id )

INSERT INTO `student`(`name`, `email`, `course`) VALUES


('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');
INSERT INTO `student`(`name`, `email`, `course`) VALUES
('test','test2@[Link]','PHP');

CodeIgniter Pagination Database Model


Create a Model "StudentPagination_Model.php" and save in
application/model

add the following code in "StudentPagination_Model" class

<?php
class StudentPagination_Model extends CI_Model
{

public function get_count()


{
return $this->db->count_all("student");
}

public function get_students($limit, $start)


{
$this->db->limit($limit, $start);
$query = $this->db->get("student");
return $query->result();
}
}
?>

CodeIgniter Pagination Controller


Create a Controller "StudentPagination_Controller.php" and save in
application/controller

add the following code in "StudentPagination_Controller" class

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class StudentPagination_Controller extends CI_Controller {

public function __construct()


{
parent:: __construct();

$this->load->helper('url','form');
$this->load->library("pagination");
$this->load->model('StudentPagination_Model');
}

public function index()


{
$config = array();
$config["base_url"] = base_url() .
"[Link]/StudentPagination_Controller/index";
$config["total_rows"] = $this->StudentPagination_Model->get_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3;

$this->pagination->initialize($config);

$page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;

$data["links"] = $this->pagination->create_links();

$data['student'] = $this->StudentPagination_Model-
>get_students($config["per_page"], $page);

$this->load->view('pagination', $data);
}
}
?>

CodeIgniter Pagination View


Create a View "[Link]" and save in application/views

add the following code in "[Link]" Page

<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Pagination Examples</title>
</head>
<body>
<div class="container">
<h2 class="text-primary">CodeIgniter Pagination Example</h2>
<table class="table table-bordered">
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
</tr>
<tbody>
<?php foreach ($student as $res): ?>
<tr>
<td><?php echo $res->id ?></td>
<td><?php echo $res->name ?></td>
<td><?php echo $res->email ?></td>
<td><?php echo $res->course ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p><?php echo $links; ?></p>
</div>
</div>
</body>
</html>

CodeIgniter Form Validation with


Example
CodeIgniter Form Validation with Example
User interaction with the application is majorly done via Forms, which is then submitted to
the database. It is mandatory to get the data correct while filling up the form so that no
gibberish data may fall into the database which makes the database junky.

The process of Form Validations helps in ensuring that the data that is submitted is correct to
store and process. Form Validations on server-side scripting are a little bit complex to handles
but Codeigniter handle the form validations much easily as it is having built-in library
functions to create forms validations.

Handling Form Validations in Codeigniter


Do the following in application/config/[Link]

Load the form helper in the autoload helper array.

$autoload['helper'] = array('form', 'url');

Include form_validation library inside autoload libraries array.

$autoload['libraries'] = array('form_validation');

You can also load the helper and libraries inside the [Link] methods by
using:

public function __construct()


{
parent::__construct();
$this->load->helper(array('form'));
$this->load->library(array('form_validation'));
}

While $autoload[ ] array helps in loading the library or helper automatically when the
application starts as it is a good practice to minimize the line of codes by not repeatedly using
same code.

Create View
Make a view file [Link] inside application/views/ This page will display the form and
which will be validated.

<html>
<head>
<title>Form</title>
</head>
<body>
<form>
<?php echo validation_errors(); ?>
<h5>Name</h5>
<input type = "text" name = "name" value = "<?php echo
set_value('name'); ?>" />
<h5>Email</h5>
<input type = "email" name = "email" value = "<?php echo
set_value('email'); ?>" />
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>
</html>

Also make a [Link] page inside application/views/ to redirect form success.

<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Form Submitted Successfully</h1>
</body>
</html>

Create Controller
Create a [Link] inside application/controller/
This page will show the form validations or print success message.

<?php
class FormController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form'));
$this->load->library(array('form_validation'));
}
public function form()
{
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('email','Email','required');

if ($this->form_validation->run() == FALSE)
{
$this->load->view('form');
}
else
{
$this->load->view('success');
}
}
}
?>

Now go to the browser and open the project :

localhost/project_folder/formcontroller/form

Enter the credentials name and email, if you enter name and email it will show the success
page else give a validation error name and email is required.

Output

Explanation:
• form_validaton library in CodeIgniter helps in checking the type of error which has various
validation rules in it. We are using the required rule above which is a validation of a required
field. (for more validation rule reference checkout Codeigniter user guide)
• Form helper helps in the form task i.e. in system/helpers/form_helper.php which helps out
with some form functions.
• In [Link] view, the validation_errors(); function shows the form validation error which
occurs during wrong credentials input.
• In [Link] $this->form_validation->set_rules('name', 'Name', 'required'); $this-
>form_validation->set_rules('email', 'Email', 'required'); Sets the validation rule for the name
and email field inside the form. Here parameters passed by set_rules(); are
set_rules('name_field', 'validation_for' , 'type_of_rule')
• If the above condition is false i.e. the required condition is not satisfied and form is not filled
up then the validation is shown with the type of validation in the form view. If it is true then
it will redirect to the success page.

Display Individual Error for every Field


<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post">
<h5>Name</h5>
<input type = "text" name = "name" value = "<?php echo
set_value('name'); ?>" />
<?php if(form_error('name'))
{
echo "<span style='color:red'>".form_error('name')."</span>";
}
?>
<h5>Email</h5>
<input type = "email" name = "email" value = "<?php echo
set_value('email'); ?>" />
<?php if(form_error('email'))
{
echo "<span style='color:red'>".form_error('email')."</span>";
}
?>

<div><input type = "submit" value = "Submit" /></div>


</form>
</body>
</html>
Output

Set Multiple Rules for a text box(Required, Minlength,


Maxlength)
$this->form_validation->set_rules('name', 'Name',
'trim|required|min_length[4]|max_length[10]');

Set Multiple Rules for a text box(Required, valid email


address)
$this->form_validation->set_rules('email', 'Email',
'required|valid_email|is_unique[[Link]]');

How to Set Session in Codeigniter With


Example
How to Set Session in Codeigniter With
Example
Keep track of the user details and what is the state of the user is
completely done using sessions. The session maintains the user state and
tracks their activity.

Maintaining the state helps in preserving the next request from the previous
one. Users don’t have to log in for each page, they can log in once and their
details are stored in a session with a session id of that user and then that
same data is reused for further request.

Codeigniter has a built-in class names ‘session’ for this purpose. The same
purpose of this session is to make the data available for the next request
made by the user.
Session Working:
When a page is requested by a user, the session class on the server checks
whether the cookie sent by the browser is valid or not. If the session cookie
is not valid or not available (expired or session expired) a new session is
created.

If there is a valid session, it will be automatically updated with the session


id. The session runs automatically once initialization is done. From reading,
writing, and updating session everything is automatic.

Session Initialization
With each page request/load on the site, session are globally run but to use
the data the initialization of session is done on the controller constructors
or can be auto-loaded in the system by session up ‘session’ in [Link]

Inside your controller you can load session by using this line of code:

$this->load->library('session');

OR in application/config/[Link] file add session library to autoload

$autoload['libraries'] = array(‘session’);

After the initialization of the session or loading session library, its object is
available using.

$this->session

Retrieval of Session Data


$_SESSION is a super-global used to avail information from a session array.
For fetching any piece of information we can simply use $_SESSION[‘item’]

In Codeigniter using magic method i.e.

$this->session->item

OR by using userdata() method which takes the parameter to be retrieved


like this:

$this->session->userdata('item');

Session can be retrieved and stored inside a variable like this:

$var = $this->session->item;
OR
$var = $this->session->userdata('item');

To get all existing userdata no parameters are passed in the method.

$this->session->userdata();

Note : Userdata() method returns NULL if no item is found.

Adding of Session Data :


Adding a session data help out in making data globally available without
running the DB query every time.

Session data can be added in key-value pairs like $_SESSION['name']='abc';

In Codeigniter it can be simply done using set_userdata(). It can be done in


two ways passing one value at a time or passing an associative array to it
like as shown below:

Passing one value at a time:

$this->session->set_userdata('some_name', 'some_value');

Passing associative array inside:

$array = array(
'name' => 'believemaster',
'email' => 'believemasters@[Link]'
);
$this->session->set_userdata($array);

where $array is associative array above containing [Link] verifyin the


session value existence has_userdata() is used

$this->session->has_userdata(‘value’);

Removing of Sessoin Data :


In Codeigniter just as set_userdata() method for adding session data there
is method called unset_userdata() for removing session data by passing the
session key.

If you want to remove name from the session which is a key value for the
session you can do it as:

$this->session->unset_userdata('name');
Unsetting the session can also be done in array format with the item key to
unset like this:

$array_list = (
'name',
'email'
);
$this->session->unset_userdata($array_list);

Session FlashData :
Session availability for only the next request and clearing it out
automatically after that is done using flash data. This is mostly used to
show one-time information i.e. error/success messages, information/status
messages, etc.

In Codeigniter set_flashdata() method is available for setting up session


available for next request only. It requires two parameters key and value
associated to that.

$this->session->set_flashdata('error', 'You have an error');


$this->session->set_flashdata('success', 'Successful');

An array can also be passed as parameter in set_flashdata()

To call the flash data, flashdata('key') method is used with a key_item


passing in the parameters to call specific flash-data or call flashdata()
without parameter to call all flashdata.

$this->session->flashdata('error'); // specific flashdata


$this->session->flashdata(); // all flashdata

For keeping flashdata for further request keep_flashdata() method is used.


Single key_item or an array can be passed as parameters.

$this->session->keep_flashdata('success');
$this->session->keep_flashdata(array('error', 'success'));

Simple Example Code for Session (using session


flash data):
Create
SessionController application/controller/SessionCon
[Link]
<?php
class SessionController extends CI_Controller
{
public function __construct()
{
parent:: __contstruct();

$this->load->helper('url');
$this->load->libraries('session');
}
public function index()
{
$this->load->view('index');
}

public function flash()


{
$this->session->set_flashdata('sess', 'session message');
redirect(base_url('[Link]/SessionController/index'));
}
}
?>

Create Index View : application/views/[Link]


<html>
<head>
<title>CI Session Flash Data</title>
</head>
<body>
<p>The session value of session is
<b><?php echo $this->session->flashdata('sess');?></b>
</p>
</body>
</html>

How to Send Email using CodeIgniter


How to Send Email using CodeIgniter
Sending email in CodeIgniter is much easier and you may set preferences in
accordance with your needs. CodeIgniter supplies an Email library to
sending email in program. Codeigniter supported inbuilt Mail library which
simplifies the email sending process.

To send mail in Codeigniter we need to do a little bit of configuration, need to load


email library.

Codeigniter supports multiple Protocols, Mail, send mail, and SMTP, multiple
recipients, CC and BCCs, HTML or Plain text email, Attachments, Word
wrapping and many more.

As you know email is quite important in web applications. When a user


signs up, we may want to send them an email to verify their email address
and allow the user to confirm subscription. We also use email to reset
forgotten passwords, send invoice and receipts to clients, etc. CodeIgniter
makes it super simple for us to send emails from our application utilizing a
variety of options.

CodeIgniter includes an integrated email library that called codeigniter


email library that we're able to work together when sending mails. In this
tutorial, we will demonstrate the mostly used email attributes like text
mail, HTML email, and email with an attachment.

CodeIgniter SMTP Email Configuration


Create a smtp configuration file [Link] inside application/config

<?php
$config = array(
'protocol' => 'smtp',
'smtp_host' => '[Link]',
'smtp_port' => 465,
'smtp_user' => 'phptpoint@[Link]
',
'smtp_pass' => '123456',
'smtp_crypto' => 'ssl',
'mailtype' => 'text',
'smtp_timeout' => '4',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
?>

Note : for sending emails to work, you should provide valid configuration
parameters. Dummy parameters will not be able to send emails.

Create a View
Create a view file inside views/[Link]

Add given below code inside the file.

<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Email Send using SMTP</title>
</head>
<body>
<div>
<h3>Use the form below to send email</h3>
<form method="post" >
<input type="email" name="to" placeholder="Enter Receiver
Email">
<br><br>
<input type="text" name="subject" placeholder="Enter Subject">
<br><br>
<textarea rows="6" name="message" placeholder="Enter your
message here"></textarea>
<br><br>
<input type="submit" value="Send Email" />
</form>
</div>
</body>
</html>

CodeIgniter Controller
Create a Controller file inside controller/EmailController .php

Add given below code inside [Link] file.

<?php
class EmailController extends CI_Controller
{

public function __construct()


{
parent:: __construct();

$this->load->helper('url');
}

public function index()


{
$this->load->view('email');
}

function send()
{
$this->load->config('email');
$this->load->library('email');

$from = $this->config->item('smtp_user');
$to = $this->input->post('to');
$subject = $this->input->post('subject');
$message = $this->input->post('message');

$this->email->set_newline("\r\n");
$this->email->from($from);
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($message);

if ($this->email->send())
{
echo 'Email has been sent successfully';
}
else
{
show_error($this->email->print_debugger());
}
}
}
?>

CodeIgniter URL Routing

CodeIgniter URL Routing


URLs in CodeIgniter are all made to be short and search engine friendly. It
should make more sense to the visitors. A user should get an idea about
the page content via its URL. So how to create Codeigniter routes learn
here below with examples.

The functionality of routes in Codeigniter is to simplify the URL and respond


with the content associated with the route and make complex URL short. A
route gives back the response to the URL requested by the user. It
simplifies the URL associated with the content. For example:

[Link]/main/home
[Link]/main/about
[Link]/main/contact
[Link]/main/login
[Link]/main/register

Routes are set after the base_url or the index_url with the controller and
method crated for routing to a specific page.

How does it work?


In the browser URL, routing structure looks something like this:

domain_name.com/Controller/Method/Parameter/

In the above URL example,


Controller points to the name of the controller (class) made during the
development i.e. controller defined in the controllers' folder, which then
binds the controller name to the URL for the response.
Method which is defined inside the controller is invoked and bound to
respond to the requested URL.
Parameter for the route is optional as it depends upon the parameters
passed while making methods/functions.
**Different class methods/functions can be called instead of one
corresponding to the URL**

Example:

localhost/user/delete/2
User = Controller,
Delete = Method inside User Controller,
2 = Parameter that method takes

Setting Up Routes :
Create a new controller in application/controller [name should be the same
as listed in [Link] in this case [Link]]
Make a class with the same name as the controller and inside define a
method loading a view.

class Main extends CI_Controller


{
public function home()
{
$this->load->view(‘home’);
}
}

Finally create a view inside application/views folder with the name


mentioned while loading inside the controller method

Application/views/[Link]

Voila! You just created your route.

The above example will be result as localhost/[Link]/main/home

**[Link] can be removed by setting up default routes in


Application/config/[Link] file**

If no matching route is found then Codeigniter throws an exception 404


Page not found.

Usage of Routes:

To build large applications with complex URLs including all routing paths
along with the fetching of id makes the URL messy and is not at all user-
friendly, also it is not at all Search Engine [Link] convention in the
URL uses query methods to pass on the request along with the extension of
a page requested.

Ex:

[Link]/admin/[Link]?q=1

Which in response is so complex and long and for a user it makes no sense.
Users should get an idea of the content present on the page through its
URL.
The easier way it can be done is

[Link]/admin/user/1

which makes more sense about the page associated with it. Using routes
URL becomes cleaner and increase the user experience in routing the web.
Moreover, URL routing helps in creating routes that are SEO friendly for
reaching the page with a quick response.

Custom Routes for Application:


As we learned about how routes work in Codeigniter. Let’s now create some
custom URL’s for our application so that we will be able to implement it in
our real-world projects. We will be implementing routes in a small blog app
where we can create, update, delete, and see blog views based on different
routes in URL.

For each function to work the controller will be the same i.e. blog and
methods inside are different. The working structure of this routing will work
something like this shown below:

/blog : shows the list of all blogs


/blog/create : shows create view for creating a blog
/blog/update/id : shows the update view with specific id
/blog/delete/id : shows the delete view with specific id
Above URL will work on the following methods called inside the controller:
/blog = index method
/blog/create = create method
/blog/update = update method
/blog/delete = delete method

Before creating a controller and view for the above structure to work.
Custom Url must be setup by creating routes for the project.
Open application/config/[Link] Add specific lines omitting the default
one.

$route[‘default_controller’] = ‘welcome’;
$route[‘blog’] = ‘blog’;
$route[‘blog/create’] = ‘blog/create’;
$route[‘blog/update/:id’] = ‘blog/update’;
$route[‘blog/delete/:id’] = ‘blog/delete’;

Explanation :
The lines on the right of equals sign are controllers and controller pointing
to the method they are calling and the lines on the left side of equals sign
defines its route where it is going or the url which is shown.
Therefore, in our scenario

$route[‘blog’] = ‘blog’; Showing the blog route pointing to the blog


controller which calls the index method inside controller.
$route[‘blog/create’] = ‘blog/create’; Showing the blog/create route pointing
the blog controller to call create method.
$route[‘blog/update/:id] = ‘blog/update; Showing the blog/update/{id} route
pointing the blog controller to call update method.
$route[‘blog/delete/:id] = ‘blog/delete; Showing the blog/delete/{id} route
pointing the blog controller to call delete method.

After all the routes are set, make a controller for the blog that will respond
to the routes specified above. Inside application/controllers make new file
[Link] and following code:

<?php
class Blog extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(‘url’);
}
public function index()
{
$this->load->view(‘index’);
}
public function create()
{
$this->load->view(‘create’);
}
public function update($id)
{
$this->load->view(‘update’);
}
public function delete($id)
{
$this->load->view(‘delete’);
}
}
?>

Here Blog controller defines all the methods we mentioned in the routes i.e.
index, create, update, delete
Now just create views for all specific methods inside applications/views/
- [Link]
- [Link]
- [Link]
- [Link]
And echo out custom message on different page.
Inside [Link] and [Link] echo $id; to see the id which you pass as
the parameter in the URL.
Open up the browser and try the following

localhost/blog
localhost/blog/create
localhost/blog/update/1
localhost/blog/delete/1

Codeigniter Tutorial PDF


Download Codeigniter Tutorial pdf for
Beginners

CodeIgniter is one of the most popular and powerful web application


development frameworks written in PHP. CodeIgniter is considered to be
quite lightweight, easy and elegant framework written in PHP. CodeIgniter
enables web developers to build full-featured web application much faster
while maintaining functionality. CodeIgniter care of all of the intricate part
in background.

This CodeIgniter tutorial pdf can help you to learn professional internet
applications development using the CodeIgniter framework.

This tutorial is made for web developers interested in learning professional


web application development using CodeIgniter framework. Here you can
download Codeigniter tutorial pdf very easily after filling some short details.

Before starting with this tutorial, you need to be familiar with site
development using PHP and MySQL, We are assuming that you're aware of
core and advance PHP concepts.

Difference between CodeIgniter vs


Laravel
Laravel vs Codeigniter
Overview
A popular open-source PHP framework which is used widely is Laravel. Web
application developed using this framework by MVC pattern. Released under
MIT license and source code is available on github open-source. A reliable
PHP framework which follow accurate rules of PHP.

A smooth PHP framework which comes in mind while working on project


is Codeigniter. It is simple and easy tool in the world of frameworks for creating
full dynamic web application fast and efficiently. It also allows third-party plugins
for adding more functionality to the project with a benefit of security and
encryption.

Pros of using Laravel

1. Main feature of laravel is inclusion of version control system helping in


management of migrations
2. Built in modules and libraries for enhanced web application.(Composer
dependency manager integrates all the modules for easy updates)
3. A powerful query builder helping in querying large DB, also giving Eloquent
i.e. Object Relational Mapper(ORM) and Active Record implementation.
4. Flexibility for setting routes in web application.
5. Various features helps in testing through various test case for maintaing the
code.
6. Configuration change is constant for maintaing in an efficient way as
different laravel websites might run on different environment and
configurations.
7. Lightweight blade template engine used to design layouts with dynamic
content.
8. Maintaining database schemas to track all changes w.r.t DB migrations.
9. Authentication features such as Register, Forgot password , send password
reminders.
10. By using LOC container new tools can be generated.

Pros of using Codeigniter


1. Lightweight framework in the category of web frameworks.
2. Easy to understand documentation with offline user guide.
3. Large codeigniter community support for immediate support.
4. Rapid PHP application development using simple routing methods and
cached websites for smooth performance.
5. Validations of forms and data with encryption, security and XSS filter
6. Includes different libraries with features used for easy development.
7. Various class extension support adding with a benefit of large helper
functions library.

Difference between Codeigniter and Laravel


Parameters Laravel Codeigniter

DBMS Support Oracle, MS SQL, MySql, DB2, MySQL, Microsoft BI, MongoDB, PostgreSQL
PostgreSQL, JDBC addon with popular databases also used in
laravel.
Popularity Getting popular day by day Less popular than laravel but for building
with more developers fast small application with all security and
community and fast coding features it is prefered mostly.
style. Preffered mostly for large
projects with heavy features
and modules.

Structure Follows MVC Structure with a MVC Structure based on Object-Oriented


command line tool 'Artisan' Programming

Modules Modularity for dividing project No built-in modularity like laravel. Modular
into different modules for easy extension used for creating and maintaing
workflow. modules.

API Support RESTful controller helps in No streamline development of REST APIs


manufacturing REST APIs
without wasting much time.

Online Help Easy to understand Built in functionality with a helpful user


documention available with guide also available offline with download.
large community working on
laravel ready to help out with
problems.

Template Simple and Robust template No specific template engine. Smarty


Engine engine i.e. Blade Template template engine tool can be used to
Engine integrate template engine. Rather its
template language is PHP proprietary

HTTP support Can define HTTPs custom Does not fully support HTTPs
routes also specific URL for
each HTTPs route.

Authentication Authentication class helps in Custom codeigniter extensions for


implementing authentication authentication, no built-in authentication
and authorization rules features.

Testing Unit testing of code can be No built-in unit testing tools. Developers
done using PHPUnit. need to reply on other testing tools for
checking application code quality.

Learning Difficult for beginners to learn Easy and very much friendly to learn for
Curve as it is stuffed with features. beginners.

Websites [Link], [Link],


Using [Link], [Link], [Link]
[Link]

Insert Data Using jQuery Ajax in


Codeigniter
How to Insert Data Using jQuery Ajax in Codeigniter
From this article, you will learn in a very simple way that to Insert Data
Using jQuery Ajax in Codeigniter. so before going further, we think that you
are a bit familiar with Codeigniter. As we know that Codeigniter is an MVC
framework that has its own functionality to insert a form of data to MySQL
database table.

Here In this ajax form submit article, We will discuss about How to use ajax
post method in Codeigniter form insert, in this, we are going to use jquery
submit handler method with jquery validation rules for ajax form
submission and Jquery submit form ajax in Codeigniter will perform without
refresh whole page with validating form data on client-side.

CodeIgniter jQuery Ajax Post Data methods really made it easy to post data
and return that data without refreshing the page. We will show you apply
this jQuery Ajax post in CodeIgniter as well.

First you need to load Library(database) as well as helper(form,url)

$autoload['helper'] = array('form', 'url');


$autoload['libraries'] = array('database');

[Link](view)
<!DOCTYPE html>
<html lang="en">
<head>
<title>save data using Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
t>
</head>
<body>
<div class="container">
<h1 align="center">Ajax Form using CI</h1>
<div class="form-group">
<label for="email">Enter Your Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter
Name" name="name">
</div>
<div class="form-group">
<label for="email">Enter Your Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter
Email" name="email">
</div>
<div class="form-group">
<label for="email">Enter Your Course:</label>
<input type="text" class="form-control" id="course" placeholder="Enter
course" name="course">
</div>
<input type="button" class="btn btn-primary" value="save data"
id="butsave">
</div>

<script type="text/javascript">

// Ajax post
$(document).ready(function()
{
$("#butsave").click(function()
{
var name = $('#name').val();
var email = $('#email').val();
var course = $('#course').val();

if(name!="" && email!="" && course!="")


{
[Link]({
type: "POST",
url: "<?php echo
base_url('/[Link]/AjaxController/savedata'); ?>",
dataType: 'html',
data: {name: name, email: email,course:course},
success: function(res)
{
if(res==1)
{
alert('Data saved successfully');
}
else
{
alert('Data not saved');
}

},
error:function()
{
alert('data not saved');
}
});
}
else
{
alert("pls fill all fields first");
}

});
});
</script>
</body>
</html>

AjaxController(Controller)
<?php
class AjaxController extends CI_Controller
{

public function index()


{
$this->load->view('Ajaxform');
}

public function savedata()


{

$data = array(
'name' => $this->input->post('name'),
'email'=>$this->input->post('email'),
'course'=>$this->input->post('course')
);

$this->load->model('AjaxModel');
$result=$this->AjaxModel->saveData($data);
if($result)
{
echo 1;
}
else
{
echo 0;
}
}
}
?>

AjaxModel(Model)
<?php
class AjaxModel extends CI_Model
{
public function saveData($data)
{
if($this->db->insert('student',$data))
{
return 1;
}
else
{
return 0;
}
}
}
?>

Output

Username availability check using


Codeigniter and AJAX
Username availability check using Codeigniter and
AJAX
In this tutorial You will learn "Check username availability using Codeigniter
Ajax and Mysql".

Sometimes, We want to check username availability instantly before the


submit button and after entering of username field. In this case "check
username availability using Codeigniter, AJAX and MySQL" technique is very
helpful.

[Link](View)
Save "[Link]" inside view folder
<!DOCTYPE html>
<html lang="en">
<head>
<title>Username availability check using Codeigniter, AJAX and MySQL</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
t>
</head>
<body>
<div class="container">
<h3 class="text-center text-primary">Username availability check using
Codeigniter, AJAX </h3>
<div class="form-group">
<label for="email">Enter Your Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter
Name" name="name">
</div>
<div class="form-group">
<label for="email">Enter Your Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter
Email" name="email">
<label id="msg"></label>
</div>
<div class="form-group">
<label for="email">Enter Your Course:</label>
<input type="text" class="form-control" id="course" placeholder="Enter
course" name="course">
</div>
<input type="button" class="btn btn-primary" value="save data"
id="butsave">
</div>

<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#email").blur(function()
{
var email = $('#email').val();

if(email!="")
{
[Link]({
type: "POST",
url: "<?php echo
base_url('/[Link]/AjaxController/checkUser'); ?>",
dataType: 'html',
data: {email: email},
success: function(res)
{
if(res==1)
{
$("#msg").css({"color":"red"});
$("#msg").html("This user already exists");
}
else
{
$("#msg").css({"color":"green"});
$("#msg").html("Congrates username available !");

},
error:function()
{
alert('some error');
}
});
}
else
{
alert("pls enter your email id ");
}

});
});
</script>
</body>
</html>

[Link](Controller)
Save "[Link]" inside controller folder

<?php
class AjaxController extends CI_Controller
{

public function index()


{
$this->load->view('Ajaxform');
}

public function checkUser()


{

$email=$this->input->post('email');

$this->load->model('AjaxModel');

$result=$this->AjaxModel->checkuser($email);
if($result)
{
echo 1;
}
else
{
echo 0;
}
}

}
?>

[Link](Model)
Save "[Link]" inside Model folder

<?php
class AjaxModel extends CI_Model
{
public function checkuser($email)
{
$this->db->where('email',$email);
$query=$this->db->get('student');
if($query->num_rows()>0)
{
return 1;
}
else
{
return 0;
}
}
}
?>

Output
:
CodeIgniter Strong Password Validation

CodeIgniter Strong Password Validation


When You are going to create a Registration Form then You should make
sure that users always must have a strong password. It's quite easy to
create a Strong password Validation with CodeIgniter, by using the Form
Validation Library and REGEX.

For example, Set the minimum and maximum length of the password, It should
contain a lowercase, uppercase, numbers, and special chars. You can also easily
make sure that the data entered in the password field Should be equal to
password confirmation field.

An example password policy could be:

• Required
• Lowercase
• Uppercase
• Number
• Special Chars

[Link](view)

<!DOCTYPE html>
<html>
<head>
<title>Strong Password Validation</title>
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
</head>
<body>
<div class="container-fluid ">
<div class="row">
<div class="col-md-9 offset-md-1">
<div class="user_about_content_box">
<div class="tab-pane">
<h3>Strong Password Validation</h3>
</div>
<div class="col-md-8">
<?php
if($this->session->flashdata('success'))
{
echo "<span class='text-success' style='font-weight:bold'>".$this->session-
>flashdata('success')."</span>";
}
?>
</div>
<form method="post" action="<?php echo
base_url('passwordcontroller/index'); ?>">
<div class="col-md-8">
<div class="form-group" id="prime_cat">
<input type="email" value="<?php echo set_value('email'); ?>"
name="email" class="form-control input-group-lg" placeholder="Email">
</div>
<?php if(form_error('email')){echo "<span
style='color:red'>".form_error('email')."</span>";} ?>

<div class="form-group" id="prime_cat">


<input type="text" value="<?php echo set_value('new_password'); ?>"
name="new_password" class="form-control input-group-lg" placeholder="New
Password">
</div>
<?php if(form_error('new_password')){echo "<span
style='color:red'>".form_error('new_password')."</span>";} ?>

<div class="form-group" id="prime_cat">


<input type="password" value="<?php echo
set_value('confirm_password'); ?>" name="confirm_password" class="form-control
input-group-lg" placeholder="Confirm Password">
</div>
<?php if(form_error('confirm_password')){echo "<span
style='color:red'>".form_error('confirm_password')."</span>";} ?>
<div class="form-group col-md-12">
<input class="btn btn-primary" type="submit" value="Create account">
</div>
</div>
</form>
</div> <!--Content box ends-->

</div>
</div>
</div>
</div>
</body>
</html>

[Link](Controller)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class PasswordController extends CI_Controller
{

public function index()


{

$rules = array(
[
'field' => 'email',
'label' => 'Email',
'rules' => 'required',
],
[
'field' => 'new_password',
'label' => 'New Password',
'rules' => 'callback_valid_password',
],
[
'field' => 'confirm_password',
'label' => 'Confirm Password',
'rules' => 'matches[new_password]',
],
);
$this->form_validation->set_rules($rules);

if($this->form_validation->run()==FALSE)
{
$this->load->view('PasswordValidation');
}
else
{

$this->session->set_flashdata('success','Congrates ');

redirect(base_url('PasswordController/index'));
}

//Create strong password


public function valid_password($password = '')
{
$password = trim($password);

$regex_lowercase = '/[a-z]/';
$regex_uppercase = '/[A-Z]/';
$regex_number = '/[0-9]/';
$regex_special = '/[!@#$%^&*()\-_=+{};:,<.>ยง~]/';

if (empty($password))
{
$this->form_validation->set_message('valid_password',
'The {field} field is required.');

return FALSE;
}

if (preg_match_all($regex_lowercase, $password) < 1)


{
$this->form_validation->set_message('valid_password',
'The {field} field must be at least one lowercase letter.');

return FALSE;
}

if (preg_match_all($regex_uppercase, $password) < 1)


{
$this->form_validation->set_message('valid_password',
'The {field} field must be at least one uppercase letter.');

return FALSE;
}

if (preg_match_all($regex_number, $password) < 1)


{
$this->form_validation->set_message('valid_password',
'The {field} field must have at least one number.');

return FALSE;
}

if (preg_match_all($regex_special, $password) < 1)


{
$this->form_validation->set_message('valid_password',
'The {field} field must have at least one special character.' . ' ' .
htmlentities('!@#$%^&*()\-_=+{};:,<.>ยง~'));

return FALSE;
}

if (strlen($password) < 5)
{
$this->form_validation->set_message('valid_password',
'The {field} field must be at least 5 characters in length.');

return FALSE;
}

if (strlen($password) > 32)


{
$this->form_validation->set_message('valid_password',
'The {field} field cannot exceed 32 characters in length.');

return FALSE;
}
return TRUE;
}
//strong password end

Output(validation
error)

Output(validation success
message)
Import CSV Data into Mysql in
Codeigniter

Import CSV Data into Mysql in Codeigniter


Bulk Data Import using CSV feature is very useful features for web
application [Link] Import feature will helps to insert bulk data
at once instead of one by one and in this way we can reduce the time for
inserting data in the database.

This CSV Import features makes it easy to insert a bunch of data in the
database on a single click.

In CodeIgniter framework, need to use a custom library to import CSV


[Link] CodeIgniter there is no system library available to import CSV data.

Through this tutorial, we are going to show you how to import CSV file data
into MySQL database in CodeIgniter.

Database table structure(tbl_user)


CREATE TABLE IF NOT EXISTS `tbl_user` (
`id` int(11) NOT NULL primary key auto_increment,
`name` varchar(250) NOT NULL,
`phone` varchar(30) NOT NULL,
`email` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Controller(Csv_import.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Csv_import extends CI_Controller


{
public function __construct()
{
parent::__construct();
$this->load->model('csv_import_model');
$this->load->library('csvimport');
}

function index()
{
$this->load->view('csv_import');
}

function display_data()
{
$result = $this->csv_import_model->select();
$output = '
<h3 align="center">User Details Imported from CSV</h3>
<div class="table table-bordered">
<table class="table table-bordered table-striped">
<tr>
<th>[Link]</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
</tr>
';
$count = 0;
if($result->num_rows() > 0)
{
foreach($result->result() as $row)
{
$count = $count + 1;
$output .= '
<tr>
<td>'.$count.'</td>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->phone.'</td>
</tr>';
}
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">Data not Available</td>
</tr>
';
}
$output .= '</table></div>';
echo $output;
}

function import_csv()
{
$file_data = $this->csvimport->get_array($_FILES["csv_file"]["tmp_name"]);
foreach($file_data as $row)
{
$data[] = array(
'name' => $row["Name"],
'phone' => $row["Phone"],
'email' => $row["Email"]
);
}
$this->csv_import_model->insert($data);
}
}

Model(Csv_import_model.php)
<?php
class Csv_import_model extends CI_Model
{
function select()
{
$this->db->order_by('id', 'DESC');
$query = $this->db->get('tbl_user');
return $query;
}

function insert($data)
{
$this->db->insert_batch('tbl_user', $data);
}
}

View(csv_import.php)

<html>
<head>
<title>How to Import CSV Data into Mysql using Codeigniter</title>
<script
src="[Link]
<link rel="stylesheet"
href="[Link] />
<script
src="[Link]
>

</head>
<body>
<div class="container box">
<h3 align="center">How to Import CSV Data into Mysql using Codeigniter</h3>

<form method="post" id="import_csv" enctype="multipart/form-data">


<div class="form-group">
<label>Select CSV File</label>
<input type="file" name="csv_file" id="csv_file" required accept=".csv" />
</div>
<br />
<button type="submit" name="import_csv" class="btn btn-info"
id="import_csv_btn">Import CSV</button>
</form>
<br />
<div id="imported_csv_data"></div>
</div>
</body>
</html>

<script>
$(document).ready(function(){

load_data();
function load_data()
{
$.ajax({
url:"<?php echo base_url(); ?>csv_import/display_data",
method:"POST",
success:function(data)
{
$('#imported_csv_data').html(data);
}
})
}

$('#import_csv').on('submit', function(event){
[Link]();
$.ajax({
url:"<?php echo base_url(); ?>csv_import/import_csv",
method:"POST",
data:new FormData(this),
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#import_csv_btn').html('Importing...');
},
success:function(data)
{
$('#import_csv')[0].reset();
$('#import_csv_btn').attr('disabled', false);
$('#import_csv_btn').html('Import Done');
load_data();
}
})
});

});
</script>

Output(Before
Uploading)
Output(after
Uploading)

Export MySQL data to CSV file in


CodeIgniter
Export MySQL data to CSV file in CodeIgniter
To import and export data CSV(Comma Separated Values) is the most
popular file format for Web Development.

You can either use fputcsv() PHP method or directly write the comma-separated
content on the file in PHP for creating CSV file.
In this tutorial, We are going to guide you how you can export MySQL data in CSV
file in CodeIgniter project.

Database table structure(tbl_user)


CREATE TABLE IF NOT EXISTS `tbl_user` (
`id` int(11) NOT NULL primary key auto_increment,
`name` varchar(250) NOT NULL,
`phone` varchar(30) NOT NULL,
`email` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Controller([Link])

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class ExportController extends CI_Controller {

public function __construct()


{
parent::__construct();
$this->load->helper('url');
$this->load->model('ExportModel');
}

public function index()


{
$data = array();
$data['usersData'] = $this->ExportModel->getUserDetails();
$this->load->view('export_view',$data);
}

// Export data in CSV format


public function exportCSV()
{

//csv file name


$filename = 'users_'.date('Ymd').'.csv';
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/csv; ");

// get data
$usersData = $this->ExportModel->getUserDetails();

// file creation
$file = fopen('php://output', 'w');

$header = array("srno","Name","Mobile","Email");
fputcsv($file, $header);

foreach ($usersData as $key=>$line){


fputcsv($file,$line);
}

fclose($file);
exit;
}
}

Model([Link])

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class ExportModel extends CI_Model
{
function getUserDetails(){

$response = array();

// Select record
$this->db->select('*');
$q = $this->db->get('tbl_user');
$response = $q->result_array();

return $response;
}

}
}

View(export_view.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script
src="[Link]
<link rel="stylesheet"
href="[Link] />
<script
src="[Link]
>
<title>Export MySQL data to CSV file in CodeIgniter</title>
</head>
<body>

<!-- Export Data -->


<a href='<?php echo base_url('/ExportController/exportCSV');
?>'>Export</a><br><br>

<!-- User Records -->


<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
</tr>
</thead>
<tbody>
<?php
foreach($usersData as $key=>$val)
{
echo "<tr>";
echo "<td>".$val['name']."</td>";
echo "<td>".$val['email']."</td>";
echo "<td>".$val['phone']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
Output

Convert HTML to PDF in CodeIgniter


using Dompdf

Convert HTML to PDF in CodeIgniter using


Dompdf
PDF is the most utilized arrangement to make the archive in the web
application. PDF record gives a straightforward and easy to use approach to
download the pack of information in a document. Before download the
website page content, the substance should be changed over from HTML to
PDF. The HTML to PDF change can be effectively done utilizing PHP library.

Convert HTML to PDF in CodeIgniter using Dompdf


PDF is the most utilized arrangement to make the archive in the web
application. PDF record gives a straightforward and easy to use approach to
download the pack of information in a document. Before download the
website page content, the substance should be changed over from HTML to
PDF. The HTML to PDF change can be effectively done utilizing PHP library.
Dompdf is a PHP library that assists with creating PDF from HTML content.
It's anything but difficult to change over HTML to PDF in PHP with Dompdf.
In the event that your application worked with CodeIgniter, a PDF library
should be made to produce PDF utilizing Dompdf. Right now, will tell you
the best way to change over HTML to pdf and produce PDF utilizing Dompdf
in CodeIgniter.

Database table structure(tbl_users)


CREATE TABLE IF NOT EXISTS `tbl_users` (
`UserID` int(11) NOT NULL primary key auto_increment,
`Name` varchar(250) NOT NULL,
`Address` text NOT NULL,
`City` varchar(250) NOT NULL,
`PostalCode` varchar(30) NOT NULL,
`Country` varchar(100) NOT NULL,
`images` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Controller(application/controllers/[Link])

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class PdfController extends CI_Controller


{
public function __construct()
{
parent::__construct();
$this->load->model('PdfModel');
$this->load->library('pdf');
}

public function index()


{
$data['customer_data'] = $this->PdfModel->showRecord();
$this->load->view('htmltopdf', $data);
}
public function details()
{
if($this->uri->segment(3))
{
$customer_id = $this->uri->segment(3);
$data['customer_details'] = $this->PdfModel-
>show_single_details($customer_id);
$this->load->view('htmltopdf', $data);
}
}

public function pdfdetails()


{
if($this->uri->segment(3))
{
$customer_id = $this->uri->segment(3);
$html_content = '<h3 align="center">Generate PDF using
Dompdf</h3>';
$html_content .= $this->PdfModel-
>show_single_details($customer_id);
$this->pdf->loadHtml($html_content);
$this->pdf->render();
$this->pdf->stream("".$customer_id.".pdf",
array("Attachment"=>0));
}
}

}
?>

Model(application/models/[Link])

<?php
class PdfModel extends CI_Model
{
function showRecord()
{
return $this->db->get('tbl_users');
}
function show_single_details($customer_id)
{
$this->db->where('UserID', $customer_id);
$data = $this->db->get('tbl_users');
$output = '<table width="100%" cellspacing="5" cellpadding="5">';
foreach($data->result() as $row)
{
$output .= '
<tr>
<td width="25%"><img
src="'.base_url().'images/'.$row->images.'" /></td>
<td width="75%">
<p><b>Name : </b>'.$row->Name.'</p>
<p><b>Address : </b>'.$row-
>Address.'</p>
<p><b>City : </b>'.$row->City.'</p>
<p><b>Postal Code : </b>'.$row-
>PostalCode.'</p>
<p><b>Country : </b> '.$row->Country.'
</p>
</td>
</tr>
';
}
$output .= '</table>';
return $output;
}
}
?>

View(application/views/[Link])

<html>
<head>
<title>Generate PDF using Dompdf</title>
<link rel="stylesheet"
href="[Link] />
</head>
<body>
<div class="container box">
<h2 class="text-center text-primary">Generate PDF using
Dompdf</h3>
<br />
<?php
if(isset($customer_data))
{
?>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>View in PDF</th>
</tr>
<?php
foreach($customer_data->result() as $row)
{
echo '
<tr>
<td>'.$row->UserID.'</td>
<td>'.$row->Name.'</td>
<td><a
href="'.base_url().'[Link]/pdfcontroller/details/'.$row-
>UserID.'">View</a></td>
<td><a
href="'.base_url().'[Link]/pdfcontroller/pdfdetails/'.$row->UserID.'">View in
PDF</a></td>
</tr>
';
}
?>
</table>
<?php
}
if(isset($customer_details))
{
echo $customer_details;
}
?>
</div>
</body>
</html>

Library(application/libraries/[Link])

<?php
error_reporting(1);
if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once 'dompdf/[Link]';

use Dompdf\Dompdf;

class Pdf extends Dompdf


{
public function __construct()
{
parent::__construct();
}
}

?>
Output(Display All
Records)

Output(Convert into pdf)


Create Custom 404 Page not found in
CodeIgniter
How to Create Custom 404 Page not found in
CodeIgniter
A custom 404 error page displayed on your screen when a page not found
error occurs. 404 Page Not Found is the most common types of error users
facing while accessing website.

In this article, we can see how to create a fully customized 404 error page
in CodeIgniter. It makes a web application user-friendly and helps the user
to go back to your website. When the user clicks on the broken link or non-
existent URL, an error message appears on the screen. A very common
cause of this situation is the broken links that point to pages or resources
that have been removed (or taken down) by the website administrator,
most of the visitors may leave your site, to overcome this problem custom
404 error page gives an opportunity to display a customized message page
with homepage redirect link.

Mainly the broken links are responsible for showing the 404(Page not found)
error page occurred. You can easily customize the 404 error page as per
your needs in CodeIgniter.

In this tutorial, we will see how to create a simple custom 404 error page in
CodeIgniter. For this, you need to create an HTML of your 404-error page.

For this, you have to Go to your web application directory and open the
file application/views/errors/html/error_404.php file in the editor. replace
error_404.php code with given below code.

After customizing error_404.php file, we will see that the custom 404 pages
have appeared like this

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>


<?php
$ci = new CI_Controller();
$ci =& get_instance();
$ci->load->helper('url');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>404 Page Not Found</title>
<link rel="stylesheet"
href="[Link]
<link href='[Link] rel='stylesheet'
type='text/css'>
<style type="text/css">
body{
background:url(<?php echo base_url(); ?>assets/front/images/[Link]);
margin:0;
background-repeat:no-repeat;
}
</style>
</head>
<body>
<div class="container" style="margin-top:200px;margin-left:550px;">
<p><a class="btn btn-warning" href="<?php echo base_url();
?>">Go Back to Home</a></p>
</div>
</body>
</html>

Output

How to insert multiple rows in MySQL


using Codeigniter

Insert multiple rows in mysql using codeigniter


In this article, we will discuss How to save Single and Multiple records from the MySQL
database using the CodeIgniter framework. if you want to enter one data on a website then we
can use the Insert Query Input method method and if you want to add multiple records to the
database we will be able to use the insert_batch Query Method.
In this step, we will add multiple rows values to CodeIgniter. So we will use
the insert_batch Query method for the example below, You can see the following example
below.

Insert multiple rows in mysql using codeigniter Core Fuction


Ex1(using default array value)

<?php
$Mydata = array(
array(
'name' => 'Your Name' ,
'email' => 'Your Email' ,
'course' => 'Your Course'
),
array(
'name' => 'Your Name' ,
'email' => 'Your Email' ,
'course' => 'Your Course'
)
);
$this->db->insert_batch('mytable', $Mydata);

//OR

$post = $this->input->post();
for ($i = 0; $i < count($post['name']; $i++)
{
$this->db->insert('my_table', array('name' => $post['name'][$i], 'email' =>
$post['email'][$i], 'course' => $post['course'][$i]));
}
?>

Examp2 Using Controller & View form templates


Views

<div class="box-body table-responsive" >


<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th class="col-md-2 col-xs-5">Name</th>
<th class="col-md-2 col-xs-3">Depmt</th>
<th class="col-md-2 col-xs-3">course</th>
</tr>
</thead>
<form method="post">
<?php for ($i=0; $i <3 ; $i++)
{?>
<tr>
<td><input type="text" name="Name[]"></td>
<td><input type="text" name="Depmt[]"></td>
<td><input type="text" name="course[]"></td>
</tr>

<?php } ?>

<tr><td colspan="3" align="center">


<input type="submit" class="btn btn-primary" value="save"></td></tr>
</form>
</table>
</div>
</div>
</div>
</body>

Controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('AdminModel');
//$this->load->helper('url');
}
public function center_details()
{

$this->form_validation->set_rules('Name[]', 'Name', 'required');


$this->form_validation->set_rules('Depmt[]', 'department',
'required');
$this->form_validation->set_rules('course[]', 'Course',
'required');

if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/center_emp_details');
}
else
{
$post = $this->input->post();
for ($i = 0; $i < count($post['Name']); $i++)
{
$data=array('name' => $post['Name'][$i],
'department' =>
$post['Depmt'][$i],
'course' =>
$post['course'][$i],);

$this->db->insert('salary',$data);

}
}
}
}
?>

Output

Codeigniter multiple drag and drop image


upload

Codeigniter multiple drag and drop image


upload
A fundamental way to upload the image
Web applications or websites are incomplete without the images. With the
help of lucrative images, one can attract the user towards their web
application. Moreover, uploading the image is the general key for web
applications. There are numerous options related to uploading the image.
Generally, developers use input with multiple uploading of images.
Somehow, it does not look attractive. Apart from it, one can also select
the [Link].
What does [Link] term stand for?
[Link] is defined as an open-source JavaScript library. By this, you will be able to drag
and drop image upload in Codeigniter. This is helpful when you are working on larval,
PHP, and any framework. Moving further, it also offers the option of image upload and
displays in Codeigniter.

It is one of the easiest ways to upload multiple images with [Link] the person
thinks about uploading the image on the web sites, then the first question strikes in his mind
is how to upload images in Codeigniter.

Here is the list of steps that will be helpful for you to image upload and display in
Codeigniter.

Step 1: Create Controller([Link]) and paste given below code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image extends CI_Controller
{
public function index()
{
$this->load->view('image');
}

public function imageUploadPost()


{
$config['upload_path'] = './img/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
$this->upload->do_upload('file');
echo "<h1>Multiple Image uploaded successfully</h1>";
exit;
}
}

Step 2: Create View([Link]) and paste given below code

<!DOCTYPE html>
<html>
<head>
<title>Codeigniter multiple drag and drop image upload</title>
<script
src="[Link]
<link rel="stylesheet"
href="[Link]
<link
href="[Link]
rel="stylesheet">
<script
src="[Link]
script>
</head>
<body>

<div class="container">
<div class="row form-group">
<form action="<?php echo base_url('Image/imageUploadPost'); ?>"
enctype="multipart/form-data" class="dropzone" id="image-upload" method="POST">
<div class="col-md-12">
<h2 class="text-primary">Codeigniter multiple drag and
drop image upload</h2>

<div>
<h3 class="text-warning">Upload Multiple
Image By Click On Box</h3>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input class="btn btn-primary btn-lg"
type="submit" value="upload"/>
</form>
</div>
</div>
</div>

<script type="text/javascript">
[Link] =
{
maxFilesize:1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
</script>

</body>
</html>

You might also like