Download as pdf or txt
Download as pdf or txt
You are on page 1of 123

https://www.studentstutorial.

com/codeigniter

1. CodeIgniter Home
CodeIgniter framework Tutorial

CodeIgniter a very popular and powerful MVC framework which is used to develop web applications.
It is a free and Open source PHP framework.

What You Should Already Know


Before you continue you should have a basic understanding of the following:

1. HTML
2. PHP

History

CodeIgniter was created by EllisLab, and is now a project of the British


Columbia Institute of Technology.

The latest version of CodeIgniter framework is 3.1.5.

License

The source code of CodeIgniter is hosted on GitHub and licensed under the
terms of MIT License.

As it is open source software, you are permitted to copy, modify and


distribute this software and its documentation for any purpose under
following conditions.

https://youtu.be/UrVzAp01_3w

2. CodeIgniter Install
How to install or setup CodeIgniter In Xampp Server

To install CodeIgniter please follow the below step:

1. Download the latest CodeIgniter by click on the download


link version from the official codeigniter website.

URL: https://codeigniter.com/

2. Unzip the file in your htdocs folder.


3. Set the baseurl by open application/config/config.php file with a
text editor.

Example
$config['base_url'] = ‘http://localhost’;

4. If you need to change the database details open


the application/config/database.php file with a text editor and set
your database settings.

Example
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'my_db',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

To chcek CodeIgniter install successfully or not open the below link in your
browser.

http://localhost/Folder name

Here CodeIgniter is my CodeIgniter project folder name.

http://localhost/CodeIgniter

https://youtu.be/UrVzAp01_3w

3. CodeIgniter Hello World


Hello world example - CodeIgniter framework

In this example we will discuss about Hello world example CodeIgniter


framework PHP.

We use two file for hello world example.

1. Hello.php (CodeIgniter\application\controllers\Hello.php )
2. hello_world.php (CodeIgniter\application\views\hello_world.php
)

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

class Hello extends CI_Controller {

public function index()


{
$this->load->view('hello_world');
}
}
?>
hello_world.php
<!DOCTYPE html>
<html>
<head>
<title>Hello World !</title>
</head>
</body>

<h1>Hello World !</h1>

</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/CodeIgniter/index.php/Hello

https://youtu.be/yvBVpz76bb8

4. CodeIgnite Remove Index


How to remove index.php from URL in CodeIgniter using .htaccess

Create a .htaccess file in root folder and add this code.

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

Before Path :

http://localhost/codeigniter/index.php/Welcome/about

After Path:

http://localhost/codeigniter/Welcome/about
https://youtu.be/tyXcc2Q4WXU

5. CodeIgniter Include Header & Footer


How to include header footer in CodeIgniter

Include header and footer is very easy in CodeIgniter.First of all create a


common file in view folder.In this example i create a file name as start.php .
Start.php(View)
<?php
include_once "header.php";
include_once $pageName.'.php';
include_once "footer.php";
?>
Home.php(view)
<!DOCTYPE html>
<html>
<head>
<title>Hello World !</title>
</head>
<body>

<h1>Main Content</h1>

</body>
</html>

header.php(View)
<h3>Header</h3>
footer.php(View)
<h3>Footer</h3>
Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class Welcome extends CI_Controller {

/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default
controller in
* config/routes.php, it's displayed at
http://example.com/
*
* So any other public methods not prefixed with an
underscore will
* map to /index.php/welcome/<method_name>
* @see
https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$data['pageName']= 'home';
$this->load->view('start',$data);
}
}

6. CodeIgniter Session
Session with example CodeIgniter framework

In CodeIgniter or any other framework session is used to store information


(in variables) and used it through out the application.

Initializing Session

To store data in session first of all we need to initialize the session.

In PHP we initialize the session by simply write


the session_start(); function.
But in CodeIgniter We can do that by executing the following line in
constructor.
$this->load->library(‘session');

Add data to session

In php we simply use $_SESSION super global variable to add value to a


session.

$_SESSION[‘key’]=value;

Same thing can be done in CodeIgniter as shown below.

$this->session->set_userdata(‘session name', ‘any value’);

set_userdata() function takes two arguments. The first argument, session


name, is the name of the session variable and here any value is the value
assign to the session. We can use set_userdata() function to pass array to
store values as shown below.

$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe@some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Remove Session Data

In PHP, we remove the data by using unset() function.


unset($_SESSION[‘some_name’]);

But in CodeIgniter we use unset_userdata() function that will remove data


from session.

$this->session->unset_userdata(‘some_name');

If you want to remove more that one value and a array data then you can
use the same function unset_userdata().

$this->session->unset_userdata($array_items);

Fetch Session Data

After set a data to a session we also retrieve it for our use. Userdata()
function will be used for this purpose.

$name = $this->session->userdata(‘name');

7. Database configuration Codeigniter framework


To connect with database in CodeIgniter you have to change config file that
store your database connection values (username, password, database name,
etc.). The config
file is located at application/config/database.php.

The config file look like this.

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);

Let’s discuss about above the config value.

Name
Description
Config

dsn The DSN connect string (an all-in-one configuration sequence).

hostname The hostname of your database server. Often this is ‘localhost’.

username The username used to connect to the database.

password The password used to connect to the database.

database The name of the database you want to connect to.

The database type. ie: mysqli, postgre, odbc, etc. Must be specified in
dbdriver
lower case.

An optional table prefix which will added to the table name when running
dbprefix Query Builder queries. This permits multiple CodeIgniter installations to
share one database.

pconnect TRUE/FALSE (boolean) - Whether to use a persistent connection.

db_debug TRUE/FALSE (boolean) - Whether database errors should be displayed.

TRUE/FALSE (boolean) - Whether database query caching is enabled, see


cache_on
also Database Caching Class.

cachedir The absolute server path to your database query cache directory.

char_set The character set used in communicating with the database.

The character collation used in communicating with the database

dbcollat Note
Only used in the ‘mysql’ and ‘mysqli’ drivers.

A default table prefix that should be swapped with dbprefix. This is useful
swap_pre for distributed applications where you might run manually written queries,
and need the prefix to still be customizable by the end user.

The database schema, defaults to ‘public’. Used by PostgreSQL and ODBC


schema
drivers.

Whether or not to use an encrypted connection.


‘mysql’ (deprecated), ‘sqlsrv’ and ‘pdo/sqlsrv’ drivers accept TRUE/FALSE
‘mysqli’ and ‘pdo/mysql’ drivers accept an array with the following
options:
‘ssl_key’ - Path to the private key file
‘ssl_cert’ - Path to the public key certificate file
encrypt ‘ssl_ca’ - Path to the certificate authority file
‘ssl_capath’ - Path to a directory containing trusted CA certificates in PEM
format
‘ssl_cipher’ - List of allowed ciphers to be used for the encryption,
separated by colons (‘:’)
‘ssl_verify’ - TRUE/FALSE; Whether to verify the server certificate or not
(‘mysqli’ only)

compress Whether or not to use client compression (MySQL only).

TRUE/FALSE (boolean) - Whether to force “Strict Mode” connections, good


stricton
for ensuring strict SQL while developing an application.

The database port number. To use this value you have to add a line to the
port database config array.
$db['default']['port'] = 5432;

8. How to insert data in database - CodeIgniter


framework
In this example we are going to show you how to insert data in database
using CodeIgniter framework PHP.
For insert
data base.data in MySQL using CodeIgniter first we have to create a table in

The INSERT INTO statement is used to insert new data to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.

For creating table the SQL query is:

SQL Query
CREATE TABLE crud (
`id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL
);

Here we using 3 files for insert data in MySQL:

• Crud.php Path: codeIgniter\application\controllers\Crud.php


• Crud_model.php Path:
codeIgniter\application\models\Crud_model.php
• insert.php Path: codeIgniter\application\views\insert.php

Crud.php (Controller)
<?php
class Crud 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('Crud_model');
}
/*Insert*/
public function savedata()
{
/*load registration view form*/
$this->load->view('insert');

/*Check submit button */


if($this->input->post('save'))
{
$data['first_name']=$this->input-
>post('first_name');
$data['last_name']=$this->input-
>post('last_name');
$data['email']=$this->input->post('email');
$response=$this->Crud_model-
>saverecords($data);
if($response==true){
echo "Records Saved Successfully";
}
else{
echo "Insert error !";
}
}
}

}
?>
Crud_model.php (Model)
<?php
class Crud_model extends CI_Model
{
function saverecords($data)
{
$this->db->insert('crud',$data);
return true;
}

}
insert.php (View)
<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
</head>

<body>
<form method="post" action="<?= base_url()
?>Crud/savedata">
<table width="600" border="1" cellspacing="5"
cellpadding="5">
<tr>
<td width="230">First Name </td>
<td width="329"><input type="text"
name="first_name"/></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="text" name="last_name"/></td>
</tr>
<tr>
<td>Email ID </td>
<td><input type="email" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
name="save" value="Save Data"/></td>
</tr>
</table>
</form>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Crud/savedata

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

https://youtu.be/7kYHOLWhJMk

9. Retrieve data from database using CodeIgniter


framework
In this example we will discuss about how to retrieve a record or data from
MySQL database using CodeIgniter framework PHP.
For retrieve
have to create
data
a table
from in
MySQL
data base.
database using CodeIgniter framework first we

After create a table in the MySQL database you need to insert record or data
on it.If you want to know how to insert data in CodeIgniter framework please
visit the link : Insert data in CodeIgniter.
The SELECT statement is used to retrieve data from one or more tables:

The SQL query for retrieve specific column.

SELECT column_name(s) FROM table_name

or we can use the * character to retrieve ALL columns from a table:

SELECT * FROM table_name

To learn more about SQL, please visit our SQL tutorial.

We use 3 file for retrieve students data.

1. Crud.php Path: application\controllers\Crud.php


2. Crud_model.php Path: application\models\Crud_model.php
3. display_records.php Path: application\views\display_records.php

Sql Table
CREATE TABLE crud (
`id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL
);
Crud.php
<?php
class Crud 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('Crud_model');
}
/*Display*/
public function displaydata()
{
$result['data']=$this->Crud_model->display_records();
$this->load->view('display_records',$result);
}
}
?>
Crud_model.php
<?php
class Crud_model extends CI_Model
{
/*View*/
function display_records()
{
$query=$this->db->get("crud");
return $query->result();
}
}
display_records.php
<html>
<head>
<title>Display records</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>

<body>
<table width="600" border="0" cellspacing="5" cellpadding="5">
<tr style="background:#CCC">
<th>Sr No</th>
<th>First_name</th>
<th>Last_name</th>
<th>Email Id</th>
</tr>
<?php
$i=1;
foreach($data as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->first_name."</td>";
echo "<td>".$row->last_name."</td>";
echo "<td>".$row->email."</td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/codeIgniter/index.php/Crud/displaydata

After fetch data the table look like this.

Id first name last name Email Id

1 Divyasundar Sahu divyasundar@gmail.com

2 Hritika Sahu hritika@gmail.com

3 Milan Jena milanjena@gmail.com

https://youtu.be/76Fn305r5xY

10. Update record CodeIgniter framework PHP


In this example we will discuss about how to update a record or data from
MySQL database using CodeIgniter framework PHP.

To update the data in mysql table UPDATE statement is used.


UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: The WHERE clause specifies which data that should be updated. If you
omit the WHERE clause, all records or data will be updated!

We use 4 file for update students data.

1. student_view.php (CodeIgniter\application\controllers\Crud.php
)
2. student_fetch.php (CodeIgniter\application\models\Crud_model.
php)
3. view_data.php (CodeIgniter\application\views\display_records.
php)
4. student_update.php (CodeIgniter\application\views\update_reco
rds.php)

Sql Table
CREATE TABLE crud (
`id` int(11) NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
PRIMARY KEY (id)
);
Crud.php (Controller file for Update)
<?php
class Crud 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('Crud_model');
}
public function dispdata()
{
$result['data']=$this->Hello_model->display_records();
$this->load->view('display_records',$result);
}
public function updatedata()
{
$id=$this->input->get('id');
$result['data']=$this->Crud_model-
>displayrecordsById($id);
$this->load->view('update_records',$result);

if($this->input->post('update'))
{
$first_name=$this->input->post('first_name');
$last_name=$this->input->post('last_name');
$email=$this->input->post('email');
$this->Crud_model-
>update_records($first_name,$last_name,$email,$id);
echo "Date updated successfully !”;
}
}
}
?>
Crud_model.php
<?php
class Crud_model extends CI_Model
{
/*Display*/
function display_records()
{
$query=$this->db->query("select * from crud");
return $query->result();
}
function displayrecordsById($id)
{
$query=$this->db->query("select * from form where
id='".$id.”’”);
return $query->result();
}
/*Update*/
function
update_records($first_name,$last_name,$email,$id)
{
$query=$this->db->query("update form SET
first_name='$first_name',last_name='$last_name',email='$email'
where id='$id’”);
}
}
display_records.php (View file for fetch data)
<!DOCTYPE html>
<html>
<head>
<title>Delete records</title>
</head>
<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr style="background:#CCC">
<th>Sr No</th>
<th>First_name</th>
<th>Last_name</th>
<th>Email Id</th>
<th>Update</th>
</tr>
<?php
$i=1;
foreach($data as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->first_name."</td>";
echo "<td>".$row->last_name."</td>";
echo "<td>".$row->email."</td>";
echo "<td><a href=‘updatedata?id=".$row-
>id."'>Update</a></td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>
update_records.php (View file for update)
<!DOCTYPE html>
<html>
<head>
<title>Update Data</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="first_name"
value="<?php echo $row->first_name; ?>"/></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="text" name="last_name" value="<?php echo
$row->last_name; ?>"/></td>
</tr>
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="email" value="<?php echo
$row->email; ?>"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="update"
value="Update_Records"/></td>
</tr>
</table>
</form>
<?php } ?>
</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/codeIgniter/index.php/Student_view

After fetch data the table look like this.

Id first name last name Email Id Action

1 Divyasundar Sahu divyasundar@gmail.com Update

2 Hritika Sahu hritika@gmail.com Update

3 Milan Jena milanjena@gmail.com Update

Now i am going to update the id 3 data. After change the data of id 3 the
table look like this.

Id first name last name Email Id Action

1 Divyasundar Sahu divyasundar@gmail.com Update

2 Hritika Sahu hritika@gmail.com Update

3 Milan Kumar Jena milanjena@gmail.com Update

11. How to delete data from database using CodeIgniter


framework
In this example we will discuss about how to delete a record or data from
MySQL database using CodeIgniter framework PHP.
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value

Notice : The WHERE clause specifies which record or records that should be
deleted. If you omit the WHERE clause, all records will be deleted!

The students table look like this:

id first name last name Email Id Action

1 Divyasundar Sahu divyasundar@gmail.com Delete

2 Hritika Sahu hritika@gmail.com Delete

3 Milan Jena milanjena@gmail.com Delete

Now i am going to delete the id=3 record.

For delete record we use 3 file here

1. Crud.php Path: codeIgniter\application\controllers\Crud.php


2. Crud_model.php Path:
codeIgniter\application\models\Crud_model.php
3. display_records.php Path:
codeIgniter\application\view\display_records.php

Crud Sql Table


CREATE TABLE crud (
`id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL
);
Crud.php
<?php
class Crud 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('Crud_model');
}
public function displaydata()
{
$result['data']=$this->Crud_model->display_records();
$this->load->view('display_records',$result);
}
/*Delete Record*/
public function deletedata()
{
$id=$this->input->get('id');
$response=$this->Crud_model->deleterecords($id);
if($response==true){
echo "Data deleted successfully !";
}
else{
echo "Error !";
}
}
}
?>
Crud_model.php
<?php
class Crud_model extends CI_Model
{
/*Display*/
function display_records()
{
$query=$this->db->get("crud");
return $query->result();
}
function deleterecords($id)
{
$this->db->where("id", $id);
$this->db->delete("crud");
return true;
}
}
display_records.php
<!DOCTYPE html>
<html>
<head>
<title>Delete records</title>
</head>
<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr style="background:#CCC">
<th>Sr No</th>
<th>First_name</th>
<th>Last_name</th>
<th>Email Id</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
$i=1;
foreach($data as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->first_name."</td>";
echo "<td>".$row->last_name."</td>";
echo "<td>".$row->email."</td>";
echo "<td><a href='deletedata?id=".$row-
>id."'>Delete</a></td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/CodeIgniter/index.php/Crud/displaydata

After delete the record the table look like this.

id first name last name Email Id Action

1 Divyasundar Sahu divyasundar@gmail.com Delete

2 Hritika Sahu hritika@gmail.com Delete

https://youtu.be/LuLMdS9fPdo

12. Get last insert id after insert query CodeIgniter


framework
In this example i am going to show you how to get the last insert id after
insert data in database.

function save_data($student_data){
$this->db->insert('student_db', $student_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}

insert_id() function will return zero if table does not have auto incremented
column so make sure table must have a column
with AUTO_INCREMENT attribute.

13. User Signup example CodeIgniter framework


In this example we will discuss about User Signup example CodeIgniter
framework.

We use two file for User Signup example CodeIgniter framework.

1. User.php (CodeIgniter\application\controllers\User.php )
2. student_registration.php (CodeIgniter\application\views\student
_registration.php)

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

public function sign_up()


{
if($this->input->post('save'))
{
$name=$this->input->post('name');
$email=$this->input->post('email');
$password=$this->input->post('pass');
$phone=$this->input->post('phone');
$que=$this->db->query("select * from user_login
where email='$email'");
$row = $que->num_rows();
if(count($row)>0)
{
$data['error']="<h3 style='color:red'>Email id
already exists</h3>";
}
else
{
$que=$this->db->query("insert into user_login
values('','$name','$email','$phone','$password')");
$data['error']="<h3 style='color:blue'>Your
account created successfully</h3>";
}

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

}
}
?>
student_registration.php
<!DOCTYPE html>
<html>
<head>
<title>Student Signup 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 Mobile </td>
<td><input type="text" name="phone"/></td>
</tr>
<tr>
<td>Enter Your Password </td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="save" value="Register
Me"/></td>
</tr>
</table>
</form>
</body>
</html>
Now run the program on your browser with the below URL:

http://localhost/CodeIgniter/index.php/User/student_registration

14. User Login example CodeIgniter framework PHP


In this example we will discuss about User Login example CodeIgniter
framework PHP.

We use two file for User Login example CodeIgniter framework.

1. User.php (CodeIgniter\application\controllers\User.php )
2. login'.php (CodeIgniter\application\views\login.php)

User.php
<?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'))
{
$email=$this->input->post('email');
$password=$this->input->post('pass');
$que=$this->db->query("select * from user_login where email='$email' and
pass='$password'");
$row = $que->num_rows();
if(count($row)>0)
{
redirect('User/dashboard');
}
else
{
$data['error']="<h3 style='color:red'>Invalid userid or password !</h3>";
}
}
$this->load->view('login',@$data);
}
function dashboard()
{
$this->load->view('dashboard');
}
}
?>

student_registration.php
<!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>

Now run the program on your browser with the below URL:

http://localhost/CodeIgniter/index.php/User/login

http://localhost/CodeIgniter/index.php/User/student_registration

15. How to change password in CodeIgniter framework


In this example we are going to show you How to change password in
CodeIgniter framework PHP.

Here we using 3 files for insert data in MySQL:

• Forms.php Path: codeIgniter\application\controllers\Forms.php


• Form_model.php Path:
codeIgniter\application\models\Form_model.php
• change_pass.php Path:
codeIgniter\application\views\change_pass.php

Forms.php (Controller)
<?php
class Forms extends CI_Controller
{
public function __construct()
{
/*call CodeIgniter's default Constructor*/
parent::__construct();
/*load database libray manually*/
$this->load->database();
$this->load->library('session');
/*load Model*/
$this->load->helper('url');
$this->load->model('Form_model');
}

public function change_pass()


{
if($this->input->post('change_pass'))
{
$old_pass=$this->input->post('old_pass');
$new_pass=$this->input->post('new_pass');
$confirm_pass=$this->input-
>post('confirm_pass');
$session_id=$this->session->userdata('id');
$que=$this->db->query("select * from
user_login where id='$session_id'");
$row=$que->row();
if((!strcmp($old_pass, $pass))&&
(!strcmp($new_pass, $confirm_pass))){
$this->Form_model-
>change_pass($session_id,$new_pass);
echo "Password changed successfully
!";
}
else{
echo "Invalid";
}
}
$this->load->view('change_pass');
}
}
?>
Form_model.php (Model)
<?php
class Form_model extends CI_Model
{
function fetch_pass($session_id)
{
$fetch_pass=$this->db->query("select * from user_login
where id='$session_id'");
$res=$fetch_pass->result();
}
function change_pass($session_id,$new_pass)
{
$update_pass=$this->db->query("UPDATE user_login set
pass='$new_pass' where id='$session_id'");
}
}
change_pass.php (View)
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link
href='//fonts.googleapis.com/css?family=Source+Sans+Pro|Open+S
ans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>

<div id="main">
<div id="login">
<?php echo @$error; ?>
<h2>Change Password</h2>
<br>
<form method="post" action=''>
<label>Old Password :</label>
<input type="password" name="old_pass" id="name"
placeholder="Old Pass"/><br /><br />
<label>New Password :</label>
<input type="password" name="new_pass"
id="password" placeholder="New Password"/><br/><br />

<label>Confirm Password :</label>


<input type="password" name="confirm_pass"
id="password" placeholder="Confirm Password"/><br/><br />
<input type="submit" value="login"
name="change_pass"/><br />
</form>
</div>
</div>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Forms/change_pass
Here codeIgniter is my folder name. Put your folder name instead
of codeIgniter.Rest of things are same.

16. How to change password in CodeIgniter framework


In this example we are going to show you How to change password in
CodeIgniter framework PHP.

Here we using 3 files for insert data in MySQL:

• Forms.php Path: codeIgniter\application\controllers\Forms.php


• Form_model.php Path:
codeIgniter\application\models\Form_model.php
• change_pass.php Path:
codeIgniter\application\views\change_pass.php

Forms.php (Controller)
<?php
class Forms extends CI_Controller
{
public function __construct()
{
/*call CodeIgniter's default Constructor*/
parent::__construct();
/*load database libray manually*/
$this->load->database();
$this->load->library('session');
/*load Model*/
$this->load->helper('url');
$this->load->model('Form_model');
}

public function change_pass()


{
if($this->input->post('change_pass'))
{
$old_pass=$this->input->post('old_pass');
$new_pass=$this->input->post('new_pass');
$confirm_pass=$this->input-
>post('confirm_pass');
$session_id=$this->session->userdata('id');
$que=$this->db->query("select * from
user_login where id='$session_id'");
$row=$que->row();
if((!strcmp($old_pass, $pass))&&
(!strcmp($new_pass, $confirm_pass))){
$this->Form_model-
>change_pass($session_id,$new_pass);
echo "Password changed successfully
!";
}
else{
echo "Invalid";
}
}
$this->load->view('change_pass');
}
}
?>
Form_model.php (Model)
<?php
class Form_model extends CI_Model
{
function fetch_pass($session_id)
{
$fetch_pass=$this->db->query("select * from user_login
where id='$session_id'");
$res=$fetch_pass->result();
}
function change_pass($session_id,$new_pass)
{
$update_pass=$this->db->query("UPDATE user_login set
pass='$new_pass' where id='$session_id'");
}
}
change_pass.php (View)
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link
href='//fonts.googleapis.com/css?family=Source+Sans+Pro|Open+S
ans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>

<div id="main">
<div id="login">
<?php echo @$error; ?>
<h2>Change Password</h2>
<br>
<form method="post" action=''>
<label>Old Password :</label>
<input type="password" name="old_pass" id="name"
placeholder="Old Pass"/><br /><br />
<label>New Password :</label>
<input type="password" name="new_pass"
id="password" placeholder="New Password"/><br/><br />

<label>Confirm Password :</label>


<input type="password" name="confirm_pass"
id="password" placeholder="Confirm Password"/><br/><br />
<input type="submit" value="login"
name="change_pass"/><br />
</form>
</div>
</div>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Forms/change_pass

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

17. How to change password in CodeIgniter framework


In this example we are going to show you How to send forgot password in
CodeIgniter framework PHP.

Here we using 2 files for insert data in MySQL:

• Forms.php Path: codeIgniter\application\controllers\Forms.php


• forgot_pass.php Path:
codeIgniter\application\views\change_pass.php

Forms.php (Controller)
<?php
class Forms extends CI_Controller
{
public function __construct()
{
/*call CodeIgniter's default Constructor*/
parent::__construct();
/*load database libray manually*/
$this->load->database();
$this->load->library('session');
/*load Model*/
$this->load->helper('url');
$this->load->model('Hello_model');
}

public function forgot_pass()


{
if($this->input->post('forgot_pass'))
{
$email=$this->input->post('email');
$que=$this->db->query("select pass,email
from user_login where email='$email'");
$row=$que->row();
$user_email=$row->email;
if((!strcmp($email, $user_email))){
$pass=$row->pass;
/*Mail Code*/
$to = $user_email;
$subject = "Password";
$txt = "Your password is $pass .";
$headers = "From:
password@example.com" . "\r\n" .
"CC: ifany@example.com";

mail($to,$subject,$txt,$headers);
}
else{
$data['error']="Invalid Email ID !";
}

}
$this->load->view('forgot_pass',@$data);
}
}
?>
forgot_pass.php (View)
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link
href='//fonts.googleapis.com/css?family=Source+Sans+Pro|Open+S
ans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>

</head>
<body>

<div id="main">
<div id="login">
<?php echo @$error; ?>
<h2>Forgot Password</h2>
<br>
<form method="post" action=''>
<label>Email ID :</label>
<input type="password" name="email" id="name"
placeholder="Email ID"/><br /><br />
<input type="submit" value="login"
name="forgot_pass"/><br />
</form>
</div>
</div>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Forms/forgot_pass

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

18. How to upload file in CodeIgniter framework


In this example we are going to show you how to how to upload file in
CodeIgniter framework.

Here we using 3 files for upload file in CodeIgniter:

• Upload.php Path:
codeIgniter\application\controllers\Upload.php
• upload_form Path:
codeIgniter\application\views\upload_form.php

Create a folder uploads under your project folder.

Upload.php (Controller)
<?php
class Upload extends CI_Controller {

public function __construct() {


parent::__construct();
$this->load->helper(array('form', 'url'));
}

public function index() {


$this->load->view('upload_form', array('error' => ' '
));
}

public function do_upload() {


$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 1200;
$this->load->library('upload', $config);

if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload-
>display_errors());
$this->load->view('upload_form', $error);
}

else {
$data = array('upload_data' => $this->upload-
>data());

echo "File uploaded Successfully!";


}
}
}
?>
upload_form.php (View)
<!DOCTYPE html>
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>

<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>

<p><?php echo anchor('upload', 'Upload Another File!');


?></p>
</body>
</html>
Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/codeIgniter/upload

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

19. How to upload Multiple file in Codeigniter


CREATE TABLE `files` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`uploaded_on` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL
DEFAULT '1' COMMENT '1=Active, 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Controller (Upload_files.php)
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class Upload_Files extends CI_Controller {


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

/* Load file model */


$this->load->model('file');
}

function index(){
$data = array();
$errorUploadType = $statusMsg = '';

/* If file upload form submitted */


if($this->input->post('fileSubmit')){

/* If files are selected to upload */


if(!empty($_FILES['files']['name']) &&
count(array_filter($_FILES['files']['name'])) > 0){
$filesCount = count($_FILES['files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['file']['name'] =
$_FILES['files']['name'][$i];
$_FILES['file']['type'] =
$_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] =
$_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] =
$_FILES['files']['error'][$i];
$_FILES['file']['size'] =
$_FILES['files']['size'][$i];

/* File upload configuration */


$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] =
'jpg|jpeg|png|gif';
/* $config['max_size'] = '100'; */
/* $config['max_width'] = '1024'; */
/* $config['max_height'] = '768'; */

/* Load and initialize upload library */


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

/* Upload file to server */


if($this->upload->do_upload('file')){
/* Uploaded file data */
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] =
$fileData['file_name'];
$uploadData[$i]['uploaded_on'] =
date("Y-m-d H:i:s");
}else{
$errorUploadType .=
$_FILES['file']['name'].' | ';
}
}

$errorUploadType =
!empty($errorUploadType)?'<br/>File Type Error:
'.trim($errorUploadType, ' | '):'';
if(!empty($uploadData)){
/* Insert files data into the database */
$insert = $this->file-
>insert($uploadData);

/* Upload status message */


$statusMsg = $insert?'Files uploaded
successfully!'.$errorUploadType:'Some problem occurred, please
try again.';
}else{
$statusMsg = "Sorry, there was an error
uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to
upload.';
}
}

/* Get files data from the database */


$data['files'] = $this->file->getRows();

/* Pass the files data to view */


$data['statusMsg'] = $statusMsg;
$this->load->view('upload_files/index', $data);
}

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

class File extends CI_Model{


function __construct() {
$this->tableName = 'files';
}

/*
* Fetch files data from the database
* @param id returns a single record if specified,
otherwise all records
*/
public function getRows($id = ''){
$this->db->select('id,file_name,uploaded_on');
$this->db->from('files');
if($id){
$this->db->where('id',$id);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('uploaded_on','desc');
$query = $this->db->get();
$result = $query->result_array();
}
return !empty($result)?$result:false;
}

/*
* Insert file data into the database
* @param array the data for inserting into the table
*/
public function insert($data = array()){
$insert = $this->db->insert_batch('files',$data);
return $insert?true:false;
}
}

View (upload_files/index.php)
<!-- Display status message -->
<?php echo !empty($statusMsg)?'<p class="status-
msg">'.$statusMsg.'</p>':''; ?>

<!-- File upload form -->


<form method="post" action="" enctype="multipart/form-data">
<div class="form-group">
<label>Choose Files</label>
<input type="file" class="form-control" name="files[]"
multiple/>
</div>
<div class="form-group">
<input class="form-control" type="submit"
name="fileSubmit" value="UPLOAD"/>
</div>
</form>
20. How to import excel and CSV file in CodeIgniter
framework MySQL
In this example we are going to show you how to How to import excel and
CSV file in CodeIgniter framework MySQL PHP.

Here we using 3 files for import data in CodeIgniter framework MySQL PHP:

• Crud.php Path: codeIgniter\application\controllers\Crud.php


• Crud_model.php Path:
codeIgniter\application\models\Crud_model.php
• import_data.php Path:
codeIgniter\application\views\import_data.php

Crud.php (Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();/* call CodeIgniter's
default Constructor */
$this->load->database();/* load database libray
manually */
$this->load->model('Crud_model');/* load Model */
}
public function importdata()
{
$this->load->view('import_data');
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;//
while(($filesop = fgetcsv($handle, 1000,
",")) !== false)
{
$fname = $filesop[0];
$lname = $filesop[1];
if($c<>0){
/* SKIP THE FIRST ROW */
$this->Crud_model-
>saverecords($fname,$lname);
}
$c = $c + 1;
}
echo "sucessfully import data !";

}
}

}
?>
Crud_model.php (Model)
<?php
class Crud_model extends CI_Model
{
function saverecords($fname,$lname)
{
$query="insert into user
values('$fname','$lname')";
$this->db->query($query);
}

}
insert.php (View)
<!DOCTYPE html>
<html>
<body>
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="submit" class="btn btn-default" name="submit"
value="submit">Upload</button>
</form>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Crud/importdata

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

21. How to export record in excel or CSV file using


CodeIgniter framework PHP
In this example we are going to show you how to how to export record in
excel or CSV file using CodeIgniter framework PHP.

Here we using 3 files for import data in CodeIgniter framework MySQL PHP:
• Crud.php Path: codeIgniter\application\controllers\Crud.php
• Crud_model.php Path:
codeIgniter\application\models\Crud_model.php
• users_view.php Path:
codeIgniter\application\views\users_view.php

Crud.php (Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();/* call CodeIgniter's
default Constructor */
$this->load->database();/* load database libray
manually */
$this->load->model('Crud_model');/* load Model */
}
public function index(){
$data['usersData'] = $this->Crud_model-
>getUserDetails();
$this->load->view('users_view',$data);
}
public function export_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->Crud_model->getUserDetails();
/* file creation */
$file = fopen('php:/* output','w'); */
$header =
array("Username","Name","Gender","Email");
fputcsv($file, $header);
foreach ($usersData as $key=>$line){
fputcsv($file,$line);
}
fclose($file);
exit;
}
}
Crud_model.php (Model)
<?php
class Crud_model extends CI_Model
{
function getUserDetails(){
$response = array();
$this->db->select('username,name,gender,email');
$q = $this->db->get('users');
$response = $q->result_array();
return $response;
}

}
users_view.php (View)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> CodeIgniter EXPORT</title>
</head>
<body>
<!-- Export Data -->
<a href='<?= base_url()
?>crud/export_csv'>Export</a><br><br>

<!-- User Records -->


<table border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Username</th>
<th>Name</th>
<th>Gender</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
foreach($usersData as $key=>$val){
echo "<tr>";
echo "<td>".$val['username']."</td>";
echo "<td>".$val['name']."</td>";
echo "<td>".$val['gender']."</td>";
echo "<td>".$val['email']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Crud

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.
22. How to insert Multiple Checkbox value in CodeIgniter
framework MySQL
In this example we are going to show you how to how to insert Multiple
Checkbox value in CodeIgniter framework MySQL PHP.

Here we using 3 files for insert Multiple Checkbox value in CodeIgniter


framework MySQL PHP:

• Crud.php Path: codeIgniter\application\controllers\Crud.php


• Crud_model.php Path:
codeIgniter\application\models\Crud_model.php
• multicheck_insert.php Path:
codeIgniter\application\views\multicheck_insert.php

Crud.php (Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();/* call CodeIgniter's
default Constructor */
$this->load->database();/* load database
libray manually */
$this->load->model('Crud_model');/* load
Model */
}
public function multicheck()
{
$this->load->view('multicheck_insert');
if(isset($_POST['save']))
{
$user_id=1;/* Pass the userid here */
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++){
$category_id = $checkbox[$i];
$this->Crud_model-
>multisave($user_id,$category_id);/* Call the modal */

}
echo "Data added successfully!";
}
}

}
?>
Crud_model.php (Model)
<?php
class Crud_model extends CI_Model
{
function multisave($user_id,$category)
{
$query="insert into user_cat
values($user_id,$category)";
$this->db->query($query);
}

insert.php (View)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="checkbox" id="checkItem" name="check[]"
value="1">Car<br>
<input type="checkbox" id="checkItem" name="check[]"
value="2">Bike<br>
<input type="checkbox" id="checkItem" name="check[]"
value="3">Cycle<br>
<button type="submit" class="btn btn-primary"
style="width:200px" name="save">Submit</button>
</form>
</body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Crud/multicheck

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

23. Pass parameter from controller to view file -


CodeIgniter framework
In this example we are going to show you how to Pass parameter from
controller to view file in CodeIgniter framework PHP.

Here we using 2 files for pass parameter from controller to view:

• parameter.php (CodeIgniter\application\controllers\parameter.
php)
• parameter_view.php (CodeIgniter\application\views\parameter_
view.php)
parameter.php
<?php
if(!defined('BASEPATH')) exit('No direct script access
allowed');
class Parameter extends CI_Controller{
/* declaring variables */
var $name;
function __construct(){
parent::__construct();
/* passing value */
$this->name="Students Tutorial";
}
function tutorial()
{
$data['name']=$this->name;
/* define variable sent to views */
$this->load->view('parameter_view',$data);
}
}
?>
parameter_view.php
<!DOCTYPE html>
<html>
<head>
<title>Passing Parameter</title>
</head>
<body>
<h3>Welcome to <?php echo $name ;?> .</h3>
</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/codeIgniter/index.php/Parameter/tutorial

Output

Welcome to Students Tutorial .

24. How to send email in CodeIgniter using SMTP


In this example we will discuss about how to send email in CodeIgniter using
SMTP PHP.

Example
public function send_mail()
{
require_once(APPPATH.'third_party/PHPMailer-
master/PHPMailerAutoload.php');
$mail = new PHPMailer();
$mail->IsSMTP(); /* we are going to use SMTP */
$mail->SMTPAuth = true; /* enabled SMTP
authentication */
$mail->SMTPSecure = "ssl"; /* prefix for secure
protocol to connect to the server */
$mail->Host = "smtp.gmail.com"; /* setting
GMail as our SMTP server */
$mail->Port = 465; /* SMTP
port to connect to GMail */
$mail->Username = "mail@gmail.com"; /* user email
address */
$mail->Password = "password"; /* password
in GMail */
$mail->SetFrom('mail@gmail.com', 'Mail'); /* Who is
sending */
$mail->isHTML(true);
$mail->Subject = "Mail Subject";
$mail->Body = '
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>Heading</h3>
<p>Message Body</p><br>
<p>With Regards</p>
<p>Your Name</p>
</body>
</html>
';
$destino = receiver@gmail.com; // Who is addressed the
email to
$mail->AddAddress($destino, "Receiver");
if(!$mail->Send()) {
return false;
}
else
{
return true;
}
}

25. How to Send message in CodeIgniter framework


In this example we will discuss about how to send message in CodeIgniter
framework PHP.
We use two file for send message in CodeIgniter framework PHP.
1. Message_send.php (CodeIgniter\application\controllers\Message
_send.php )
2. hello_world.php (CodeIgniter\application\views\message.php)

Message_send.php
<?php
class Message_send extends CI_Controller
{
public function __construct()
{
/*call CodeIgniter's default Constructor*/
parent::__construct();
}
public function message()
{
/*load registration view form*/
$this->load->view('message');

/*Check submit button */


if($this->input->post('save'))
{
$phone=$this->input->post(‘phone’);
$user_message=$this->input->post(‘message’);
/*Your authentication key*/
$authKey = "3456655757gEr5a019b18";
/*Multiple mobiles numbers separated by comma*/
$mobileNumber = $phone;
/*Sender ID,While using route4 sender id should be 6
characters long.*/
$senderId = "ABCDEF";
/*Your message to send, Add URL encoding here.*/
$message = $user_message;
/*Define route */
$route = "route=4";
/*Prepare you post parameters*/
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
/*API URL*/
$url="https://control.msg91.com/api/sendhttp.php";
/* init the resource */
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
/*,CURLOPT_FOLLOWLOCATION => true*/
));
/*Ignore SSL certificate verification*/
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
/*get response*/
$output = curl_exec($ch);
/*Print error if any*/
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo “Message Sent Successfully !";
}
}
}
?>
message.php
<!DOCTYPE html>
<html>
<head>
<title>Send Message</title>
</head>

<body>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="phone"/></td>
</tr>

<tr>
<td>Enter Your Message</td>
<td><textarea rows="4" cols="50" name="message">

</textarea></td>
</tr>

<tr>
<td colspan="2" align="center"><input type="submit"
name="save" value="Save Data"/></td>
</tr>
</table>

</form>
</body>
</html>
Now run the program on your browser with the below URL:

http://localhost/CodeIgniter/index.php/Message_send/message

26. How to integrate OTP in CodeIgniter framework PHP


Still unable to integrate OTP. Hire an expert at only INR 700.00/-
Rupees Or $10. Please contact us info@studentstutorial.com, +91
9437911966

Pay NowContact Now

In this example we will discuss about how to integrate OTP in CodeIgniter framework PHP.

We use two file for send message in CodeIgniter framework PHP.

1. OTP_send.php (CodeIgniter\application\controllers\OTP_send.p
hp )
2. sign_up.php (CodeIgniter\application\views\signup.php)

OTP_send.php
<?php
class Message_send extends CI_Controller
{
public function __construct()
{
/*call CodeIgniter's default Constructor*/
parent::__construct();
}
public function message()
{
/*load registration view form*/
$this->load->view('signup');

/*Check submit button */


if($this->input->post('save'))
{
$phone=$this->input->post(‘phone’);
$user_message=$this->input->post(‘message’);
/*Your authentication key*/
$authKey = "3456655757gEr5a019b18";
/*Multiple mobiles numbers separated by comma*/
$mobileNumber = $phone;
/*Sender ID,While using route4 sender id should be 6
characters long.*/
$senderId = "ABCDEF";
/*Your message to send, Add URL encoding here.*/
$rndno=rand(1000, 9999);
$message = urlencode(“OTP number.".$rndno);
/*Define route */
$route = "route=4";
/*Prepare you post parameters*/
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
/*API URL*/
$url="https://control.msg91.com/api/sendhttp.php";
/* init the resource*/
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
/*,CURLOPT_FOLLOWLOCATION => true));*/
/*Ignore SSL certificate verification*/
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
/*get response*/
$output = curl_exec($ch);
/*Print error if any*/
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);

echo “OTP Sent Successfully !";


}
}
}
?>
sign_up.php
<!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">First Name </td>
<td width="329"><input type="text" name="name"/></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="text" name="phone"/></td>
</tr>
<tr>
<td>Email ID </td>
<td><input type="email" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
name="save" value="Save Data"/></td>
</tr>
</table>
</form>
</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/CodeIgniter/index.php/OTP_send/signup

27. Show total amount month and year wise CodeIgniter


framework PHP
In this example we will discuss about how to show total amount month and
year wise from database table using CodeIgniter framework PHP.

For show total amount month and year wise we use 3 file here

1. total_amount.php (CodeIgniter\application\controllers\total_am
ount.php )
2. data_fetch.php (CodeIgniter\application\models\data_fetch.php
)
3. view_total_amount.php (CodeIgniter\application\vie\view_total_
amount.php)

total_amount.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
class Total_amount extends CI_Controller {
public function __construct()
{
parent::__construct();

/* calling model */
$this->load->model("Data_fetch", "a");
}

public function index()


{
$this->load->view("view_total_amount");
}
}
?>
data_fetch.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class Data_fetch extends CI_Model {

function __construct()
{
/*call model constructor */
parent::__construct();
}

function fetchtable()
{
$query = $this->db->query('select year(date) as
year, month(date) as month, sum(paid) as total_amount from
amount_table group by year(date), month(date)');

return $query->result();
}
}
?>
view_total_amount.php
<!DOCTYPE html>
<html>
<body>
<style>
table, td, th {
border: 1px solid #ddd;
text-align: left;
}

table {
border-collapse: collapse;
width: 40%;
}

th, td {
padding: 13px;
}
</style>
<table>
<thead>
<th>Year</th>
<th>Month</th>
<th>Total Amount</th>

</thead>
<tbody>
<?php
foreach($this->a->fetchtable() as $row)
{
$monthNum = $row->month;
$dateObj = DateTime::createFromFormat('!m',
$monthNum);
$monthName = $dateObj->format('F');
/*name has to be same as in the database.
*/
echo "<tr>
<td>$row->year</td>
<td>$monthName</td>
<td>$row->total_amount</td>

</tr>";
}
?>
</tbody>
</table>
</body>
</html>

Now run the program on your browser with the below URL:

http://localhost/codeIgniter/index.php/Total_amount

This is my database table

After run the code i get the output

Output

Year Month Total Amount

2016 August 150

2017 August 150

2017 September 300


Thank you !

28. Pagination in Codeigniter Mysqli With Example and


Demo
Create a new model Students_model in application/models.

Students_model.php
<?php
class Students_model extends CI_Model {
protected $table = 'students_data';
public function __construct() {
parent::__construct();
}
public function get_count() {
return $this->db->count_all($this->table);
}
public function get_students($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get($this->table);
return $query->result();
}
}
Create a new file Students.php in application/controllers directory
Students.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
class Students extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->helper('url');
$this->load->model('students_model');
$this->load->library("pagination");
}
public function index() {
$config = array();
$config["base_url"] = base_url() . "students";
$config["total_rows"] = $this->students_model-
>get_count();
$config["per_page"] = 10;
$config["uri_segment"] = 2;
$this->pagination->initialize($config);
$page = ($this->uri->segment(2)) ? $this->uri-
>segment(2) : 0;
$data["links"] = $this->pagination-
>create_links();
$data['students'] = $this->students_model-
>get_authors($config["per_page"], $page);
$this->load->view('students/index', $data);
}
}

Create a new file index.php in application/views/students/index.php

index.php
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Pagination</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<div class="container">
<h3>CodeIgniter Database Pagination</h3>
<div class="column">
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<?php foreach ($students as $student):
?>
<tr>
<td><?= $student->id; ?></td>
<td><?= $student->first_name;
?></td>
<td><?= $student->last_name;
?></td>
<td><?= $student->email;
?></td>
<td><?= $student->phone
;?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p><?php echo $links; ?></p>
</div>
</div>
</body>
</html>

29. How to send mail using PHP mailer Codeigniter


Step 1: Download PHP mailer from the link.

Step 2: Then store it in thirdparty folder in application

Step 3: Then create a file name as phpmailer.php in


application/libraries/phpmailer.php.

application/libraries/phpmailer.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class PHPMailer_Lib
{
public function __construct(){
log_message('Debug', 'PHPMailer class is loaded.');
}

public function load(){


require_once
APPPATH.'third_party/PHPMailer/Exception.php';
require_once
APPPATH.'third_party/PHPMailer/PHPMailer.php';
require_once APPPATH.'third_party/PHPMailer/SMTP.php';

$mail = new PHPMailer;


return $mail;
}
}
tep 4: Then create the controller file.
Mail.php(CI_Controller)
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class Email extends CI_Controller{

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

function send(){
/* Load PHPMailer library */
$this->load->library('phpmailer');

/* PHPMailer object */
$mail = $this->phpmailer->load();

/* SMTP configuration */
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = '********';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

$mail->setFrom('info@example.com', 'CodexWorld');
$mail->addReplyTo('info@example.com', 'CodexWorld');

/* Add a recipient */
$mail->addAddress('divyasundarsahu@gmail.com');

/* Add cc or bcc */
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

/* Email subject */
$mail->Subject = 'Send Email via SMTP using PHPMailer
in CodeIgniter';

/* Set email format to HTML */


$mail->isHTML(true);

/* Email body content */


$mailContent = "<h1>Send HTML Email using SMTP in
CodeIgniter</h1>
<p>This is a test email sending using SMTP mail server
with PHPMailer.</p>";
$mail->Body = $mailContent;
/* Send email */
if(!$mail->send()){
echo 'Mail could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Mail has been sent';
}
}

30. How to Remove index.php of Codeigniter on IIS


index.php
<?xml version="1.0" encoding="UTF-8"? >
<configuration >

<system.webServer >

<httpErrors errorMode="Detailed" / >


<asp scriptErrorSentToBrowser="true"/ >

<rewrite >
<rules >
<rule name="RuleRemoveIndex"
stopProcessing="true" >
<match url="^(.*)$" ignoreCase="false" / >
<conditions >
<add input="{REQUEST_FILENAME}"
matchType="IsFile" ignoreCase="false" negate="true" / >
<add input="{REQUEST_FILENAME}"
matchType="IsDirectory" ignoreCase="false" negate="true" / >
</conditions >
<action type="Rewrite" url="index.php/{R:1}"
appendQueryString="true"/ >
</rule >
</rules >
</rewrite >

</system.webServer >

<system.web >
<customErrors mode="Off"/ >
<compilation debug="true"/ >
</system.web >

</configuration >

31. Get convert currency in codeigniter


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

class Convert extends CI_Controller {


public function __construct()
{
parent::__construct();
/* if ($this- >session- >userdata('logged_in') !=
1){
redirect('home');
} */
}
public function index(){

$this- >load- >view('index.php');


}
public function convert(){
function
currencyConverter($fromCurrency,$toCurrency,$amount) {
$fromCurrency = urlencode($fromCurrency);
$toCurrency = urlencode($toCurrency);
$encode_amount = 1;
$url =
"https://www.google.com/search?q=".$fromCurrency."+to+".$toCur
rency;
$get = file_get_contents($url);
$data = preg_split('/\D\s(.*?)\s=\s/',$get);
$exhangeRate = (float) substr($data[1],0,7);
$convertedAmount = $amount*$exhangeRate;
$data = array( 'exhangeRate' = > $exhangeRate,
'convertedAmount' = >$convertedAmount, 'fromCurrency' = >
strtoupper($fromCurrency), 'toCurrency' = >
strtoupper($toCurrency));
echo json_encode( $data );
}
if(1==1) {
$from_currency = trim($_POST['from_currency']);
$to_currency = trim($_POST['to_currency']);
$amount = trim($_POST['amount']);
if($from_currency == $to_currency) {
$data = array('error' = > '1');
echo json_encode( $data );
exit;
}
$converted_currency=currencyConverter($from_currency,
$to_currency, $amount);
echo $converted_currency;
}
}
index.php
<!DOCTYPE html >
<html >
<head >
<title >Current Weather </title >
</head>
<body>
<div class="card">
<div class="card-body">
<div class="text-dark font-size-18 font-weight-bold mb-
1" >Currency XE </div>
<form method="post" id="currency-form">
<div class="form-group" >
<label >From </label>
<select name="from_currency" class="form-control">
<option value="INR" >Indian Rupee </option>
<option value="USD" selected="1" >US Dollar
</option>
<option value="AUD" >Australian Dollar
</option>
<option value="EUR" >Euro </option >
<option value="EGP" >Egyptian Pound
</option>
<option value="CNY" >Chinese Yuan </option>
</select >
<label >Amount </label>
<input type="text" placeholder="Currency"
name="amount" class="form-control" id="amount" />

<label >To </label >


<select name="to_currency" class="form-control">
<option value="INR" selected="1" >Indian
Rupee </option>
<option value="USD" >US Dollar </option>
<option value="AUD" >Australian Dollar
</option>
<option value="EUR" >Euro </option >
<option value="EGP" >Egyptian Pound
</option>
<option value="CNY" >Chinese Yuan </option>
</select>
<br>
<button type="button" name="convert" id="convert"
class="btn btn-default" >Convert</button>

</div>
</form>
<div class="form-group" id="converted_rate" > </div>

<div id="converted_amount"> </div>


</div>
</div>
$('document').ready(function() {

/* Handling Currency Convert functionality */


$('#convert').on('click', function() {
var data = $("#currency-form").serialize();

$.ajax({
type : 'POST',
url : 'http://localhost/trading_new/Dashboard/convert',
dataType:'json',
data : data,
beforeSend: function(){
$("#convert").html(' <span class="glyphicon
glyphicon-transfer" > </span > converting ...');
},
success : function(response){
//alert(response);
if(response.error == 1){
$("#converted_rate").html(' <span class="form-
group has-error" >Error: Please select different currency
</span >');
$("#converted_amount").html("");
$("#convert").html('Convert');
$("#converted_rate").show();
} else if(response.exhangeRate){

$("#converted_rate").html(" <strong >Exchange Rate


("+response.toCurrency+" </strong >) :
"+response.exhangeRate);
$("#converted_rate").show();
$("#converted_amount").html(" <strong >Converted
Amount ("+response.toCurrency+" </strong >) :
"+response.convertedAmount);
$("#converted_amount").show();
$("#convert").html('Convert');
} else {
$("#converted_rate").html("No Result");
$("#converted_rate").show();
$("#converted_amount").html("");
}
}
});
});

});
</body >
</html >

32. Codeigniter Google News


index.php
<!DOCTYPE html >
<html >
<head >
<title >Current Weather </title >
</head >
<body >
<!--NEWS-->
<div class="card" >
<div class="card-body" >
<ul class="list-unstyled" >
<?php
for ($x = 0; $x <= 9; $x++) {
? >
<li class="kit_l15_item" >
<a href=" <?php echo
ucwords($newsdata- >articles[$x]- >url); ? >"
class="kit_l15_itemLink" >
<div class="kit_l15_itemCover mr-
3" >
<img src=" <?php echo
$newsdata- >articles[$x]- >urlToImage; ? >" alt="Hands" >
</div >
<div >
<div class="text-blue" > <?php
echo ucwords($newsdata- >articles[$x]- >title); ? > </div >
<div class="font-weight-bold
mb-2" > <?php echo ucwords($newsdata- >articles[1]-
>publishedAt); ? > </div >
<div>
<?php echo ucwords($newsdata-
>articles[1]- >description); ? >
</div>
</div >
</a >
</li >
<?php
}
? >
</ul >

</div >
</div >
<!--NEWS END-->
</body >
</html >

33. CodeIgniter Form Valdition Example


Rule Parameter Description Example

Returns FALSE if
required No the form element
is empty.

Returns FALSE if
the form element
matches Yes does not match matches[form_item]
the one in the
parameter.

Returns FALSE if
the form element
regex_match Yes does not match regex_match[/regex/]
the regular
expression.

Returns FALSE if
the form element
differs Yes does not differ differs[form_item]
from the one in
the parameter.

Returns FALSE if
the form element
is not unique to
the table and field
name in the
is_unique Yes parameter. Note: is_unique[table.field]
This rule
requires Query
Builder to be
enabled in order
to work.

Returns FALSE if
the form element
min_length Yes min_length[3]
is shorter than the
parameter value.

max_length Yes Returns FALSE if max_length[12]


the form element
is longer than the
parameter value.

Returns FALSE if
the form element
exact_length Yes exact_length[8]
is not exactly the
parameter value.

Returns FALSE if
the form element
is less than or
greater_than Yes greater_than[8]
equal to the
parameter value
or not numeric.

Returns FALSE if
the form element
greater_than_equal_to Yes is less than the greater_than_equal_to[8]
parameter value,
or not numeric.

Returns FALSE if
the form element
is greater than or
less_than Yes less_than[8]
equal to the
parameter value
or not numeric.

Returns FALSE if
the form element
less_than_equal_to Yes is greater than the less_than_equal_to[8]
parameter value,
or not numeric.

Returns FALSE if
the form element
in_list Yes is not within a in_list[red,blue,green]
predetermined
list.

Returns FALSE if
alpha No the form element
contains anything
other than
alphabetical
characters.

Returns FALSE if
the form element
contains anything
alpha_numeric No
other than alpha-
numeric
characters.

Returns FALSE if
the form element
contains anything
other than alpha-
numeric
alpha_numeric_spaces No characters or
spaces. Should
be used after trim
to avoid spaces at
the beginning or
end.

Returns FALSE if
the form element
contains anything
other than alpha-
alpha_dash No
numeric
characters,
underscores or
dashes.

Returns FALSE if
the form element
contains anything
numeric No
other than
numeric
characters.

Returns FALSE if
the form element
integer No contains anything
other than an
integer.
Returns FALSE if
the form element
decimal No contains anything
other than a
decimal number.

Returns FALSE if
the form element
contains anything
is_natural No
other than a
natural number: 0,
1, 2, 3, etc.

Returns FALSE if
the form element
contains anything
is_natural_no_zero No other than a
natural number,
but not zero: 1, 2,
3, etc.

Returns FALSE if
the form element
valid_url No
does not contain
a valid URL.

Returns FALSE if
the form element
valid_email No does not contain
a valid email
address.

Returns FALSE if
any value
provided in a
valid_emails No
comma separated
list is not a valid
email.

Returns FALSE if
the supplied IP
valid_ip Yes address is not
valid. Accepts an
optional
parameter of
‘ipv4’ or ‘ipv6’ to
specify an IP
format.

Returns FALSE if
the supplied string
contains anything
valid_base64 No
other than valid
Base64
characters.

34. Codeigniter Batch Insert Example


$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);

$this->db->insert_batch('mytable', $data);
Produces: INSERT INTO mytable (title, name, date) VALUES ('My
title', 'My name', 'My date'), ('Another title', 'Another
name', 'Another date')
Using For each
$final_data=array();
foreach($service_ids as $service_id){
array_push($final_data, array(
'FileID'=>$insert_id,
'ServiceID'=>(int)$service_id

));
$counter ++;
}

$this->db->insert_batch('filedocument', $final_data);

35. CodeIgniter TCPDF Integration


Step 1: To Download TCPDF Click Here.
Step 2: Unzip the above download inside application/libraries/tcpdf.

Step 3: Create a new file inside application/libraries/Pdf.php

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


access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{
function __construct()
{
parent::__construct();
}
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */
Step 4: Create Controller file inside application/controllers/pdfexample.php.
<?php
class pdfexample extends CI_Controller{
function __construct() {
parent::__construct();
}
function index()
{
$this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Pdf Example');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'CodeIgniter TCPDF Integration');
$pdf->Output('pdfexample.pdf', 'I');
}
}
?>

36. How to use joins in codeIgniter


Normal Join
$this->db->select('*');
$this->db->from('articles');
$this->db->join('category', 'category.id = articles.id');

$query = $this->db->get();
/* Produces: */
/* SELECT * FROM articles JOIN category ON category.id =
articles.id */

Join With Condition


$this->db->select('*');
$this->db->from('articles');
$this->db->join('category', 'category.id = articles.id');
$this->db->where(array('category.id' => 10));

$query = $this->db->get();

/* Produces: */
/* SELECT * FROM articles JOIN category ON category.id =
articles.id where category.id = 10 */

Join with multiple tables


$this->db->select('*');
$this->db->from('articles');
$this->db->join('category', 'category.id = articles.id');
$this->db->join('comments', 'comments.id = articles.id');

$query = $this->db->get();

/* Produces: */
/* SELECT * FROM articles */
/* JOIN category ON category.id = articles.id */
/* JOIN comments ON comments.id = articles.id */

Join with specific type (left, right, outer, inner, left outer, and
right outer)
$this->db->select('*');
$this->db->from('articles');
$this->db->join('category', 'category.id =
articles.id','left');
$this->db->join('comments', 'comments.id =
articles.id','left');

$query = $this->db->get();

/* Produces: */
/* SELECT * FROM articles */
/* LEFT JOIN category ON category.id = articles.id */
/* LEFT JOIN comments ON comments.id = articles.id */

37. Difference between result() and row() in codeigniter


result() To fetch multiple records from the database table we need to use
result().

row()To fetch a single record from the database table we need to use row().

Example:

result():
$query = $this->db->query("YOUR QUERY");

$data=$query->result();

foreach ($data as $row) {

echo $row['title'];

echo $row['name'];

echo $row['body'];

row()

result():
$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0) {

$row = $query->row_array();

echo $row['title'];

echo $row['name'];

echo $row['body'];

38. CodeIgniter Like Query Example


In the codeigniter framework, we have to use the function $this->db->like();
to generate the LIKE clause. It should be used along with codeigniter select
query to automatically generate where and like operators.

$this->db->like('column', 'pattern');<br> // Generates: WHERE column LIKE


'%pattern%'

Take this mysql table 'student' as an example.


id StudentName Roll-No Age Country

1 John Sili 1058 24 India

2 Jhon 1059 22 Delhi

3 Sili 1060 24 Delhi

This like query in codeigniter searches the table 'student' for the records
having the substring 'sili' in the column 'StudentName'.

$this->db->select('*');

$this->db->from('Books');

$this->db->like('BookName', 'Power');

$query = $this->db->get();

// Produces SQL:

// SELECT * FROM Books WHERE BookName LIKE '%Power%';


Query Result:

id StudentName Roll-No Age Country

1 john Sili 1058 24 India

3 Sili 1060 24 Delhi

39. How to Export MySQL Table to JSON File in


CodeIgniter
SQL Query
CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE IF NOT EXISTS `users` (


`id` int(10) NOT NULL AUTO_INCREMENT,
`fname` varchar(30) NOT NULL,
`lname` varchar(30) NOT NULL,
`email` varchar(60) NOT NULL,
`city` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `users` (`id`, `fname`, `lname`, `email`, `city`)


VALUES
(1, 'anti', 'warner', 'warneranti34@yahoo.com', 'Las Vegas'),
(2, 'john', 'Taylor', 'taylorjohn@yahoo.com', 'San
Francisco'),
(3, 'santener', 'Greyson', 'santener@gmail.com', 'New York'),
(4, 'Henry', 'lee', 'henrylee@gmail.com', 'Los Angeles'),
(5, 'jack', 'kelly', 'jack12@gmail.com', 'New York');

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

function toJSON()
{
$query = $this->db->get('users');
return json_encode($query->result(),
JSON_PRETTY_PRINT);
}
}
?>
UserController.php
<?php
class UserController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('file');
$this->load->database();
}

public function index()


{
$this->load->model('UserModel');
$result = $this->UserModel->toJSON();
if(write_file('user_data.json', $result))
echo 'Successfully exported to json file!';
else
echo 'Error exporting mysql data...';
}
}
?>
user_data.json
[
{
"id": "1",
"fname": "anti",
"lname": "warner",
"email": "warneranti34@yahoo.com",
"city": "Las Vegas"
},
{
"id": "2",
"fname": "john",
"lname": "Taylor",
"email": "taylorjohn@yahoo.com",
"city": "San Francisco"
},
{
"id": "3",
"fname": "santener",
"lname": "Greyson",
"email": "santener@gmail.com",
"city": "New York"
},
{
"id": "4",
"fname": "Henry",
"lname": "lee",
"email": "henrylee@gmail.com",
"city": "Los Angeles"
},
{
"id": "5",
"fname": "jack",
"lname": "kelly",
"email": "jack12@gmail.com",
"city": "New York"
}
]

40. How to Login with Facebook in CodeIgniter


Sql Table
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oauth_provider` enum('facebook','google','twitter','')
COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`link` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
autoload.php
$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url');
facebook.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

/*
| ------------------------------------------------------------
-------
| Facebook API Configuration
| ------------------------------------------------------------
-------
|
| To get an facebook app details you have to create a Facebook
app
| at Facebook developers panel
(https://developers.facebook.com)
|
| facebook_app_id string Your Facebook App
ID.
| facebook_app_secret string Your Facebook App
Secret.
| facebook_login_redirect_url string URL to redirect back
to after login. (do not include base URL)
| facebook_logout_redirect_url string URL to redirect back
to after logout. (do not include base URL)
| facebook_login_type string Set login type.
(web, js, canvas)
| facebook_permissions array Your required
permissions.
| facebook_graph_version string Specify Facebook
Graph version. Eg v3.2
| facebook_auth_on_load boolean Set to TRUE to check
for valid access token on every page load.
*/
$config['facebook_app_id'] =
'Insert_Facebook_App_ID';
$config['facebook_app_secret'] =
'Insert_Facebook_App_Secret';
$config['facebook_login_redirect_url'] =
'user_authentication/';
$config['facebook_logout_redirect_url'] =
'user_authentication/logout';
$config['facebook_login_type'] = 'web';
$config['facebook_permissions'] = array('email');
$config['facebook_graph_version'] = 'v3.2';
$config['facebook_auth_on_load'] = TRUE;
Facebook.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

/**
* Facebook PHP SDK v5 for CodeIgniter 3.x
*
* Library for Facebook PHP SDK v5. It helps the user to login
with their Facebook account
* in CodeIgniter application.
*
* This library requires the Facebook PHP SDK v5 and it should
be placed in libraries folder.
*
* It also requires social configuration file and it should be
placed in the config directory.
*
* @package CodeIgniter
* @category Libraries
* @author CodexWorld
* @license http://www.codexworld.com/license/
* @link http://www.codexworld.com
* @version 3.0
*/

/* Include the autoloader provided in the SDK */


require_once APPPATH .'third_party/facebook-php-graph-
sdk/autoload.php';

use Facebook\Facebook as FB;


use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Helpers\FacebookJavaScriptHelper;
use Facebook\Helpers\FacebookRedirectLoginHelper;
Class Facebook
{
/**
* @var FB
*/
private $fb;
/**
* @var
FacebookRedirectLoginHelper|FacebookJavaScriptHelper
*/
private $helper;

/**
* Facebook constructor.
*/
public function __construct(){
/* Load fb config */
$this->load->config('facebook');
/* Load required libraries and helpers */
$this->load->library('session');
$this->load->helper('url');
if (!isset($this->fb)){
$this->fb = new FB([
'app_id' => $this->config-
>item('facebook_app_id'),
'app_secret' => $this->config-
>item('facebook_app_secret'),
'default_graph_version' => $this->config-
>item('facebook_graph_version')
]);
}
/* Load correct helper depending on login type */
/* set in the config file */
switch ($this->config->item('facebook_login_type')){
case 'js':
$this->helper = $this->fb-
>getJavaScriptHelper();
break;
case 'canvas':
$this->helper = $this->fb->getCanvasHelper();
break;
case 'page_tab':
$this->helper = $this->fb->getPageTabHelper();
break;
case 'web':
$this->helper = $this->fb-
>getRedirectLoginHelper();
break;
}
if ($this->config->item('facebook_auth_on_load') ===
TRUE){
/* Try and authenticate the user right away (get
valid access token) */
$this->authenticate();
}
}

/**
* @return FB
*/
public function object(){
return $this->fb;
}

/**
* Check whether the user is logged in.
* by access token
*
* @return mixed|boolean
*/
public function is_authenticated(){
$access_token = $this->authenticate();
if(isset($access_token)){
return $access_token;
}
return false;
}

/**
* Do Graph request
*
* @param $method
* @param $endpoint
* @param array $params
* @param null $access_token
*
* @return array
*/
public function request($method, $endpoint, $params = [],
$access_token = null){
try{
$response = $this->fb-
>{strtolower($method)}($endpoint, $params, $access_token);
return $response->getDecodedBody();
}catch(FacebookResponseException $e){
return $this->logError($e->getCode(), $e-
>getMessage());
}catch (FacebookSDKException $e){
return $this->logError($e->getCode(), $e-
>getMessage());
}
}

/**
* Generate Facebook login url for web
*
* @return string
*/
public function login_url(){
/* Login type must be web, else return empty string */
if($this->config->item('facebook_login_type') !=
'web'){
return '';
}
/* Get login url */
return $this->helper->getLoginUrl(
base_url() . $this->config-
>item('facebook_login_redirect_url'),
$this->config->item('facebook_permissions')
);
}

/**
* Generate Facebook logout url for web
*
* @return string
*/
public function logout_url(){
/* Login type must be web, else return empty string */
if($this->config->item('facebook_login_type') !=
'web'){
return '';
}
/* Get logout url */
return $this->helper->getLogoutUrl(
$this->get_access_token(),
base_url() . $this->config-
>item('facebook_logout_redirect_url')
);
}

/**
* Destroy local Facebook session
*/
public function destroy_session(){
$this->session->unset_userdata('fb_access_token');
}

/**
* Get a new access token from Facebook
*
* @return array|AccessToken|null|object|void
*/
private function authenticate(){
$access_token = $this->get_access_token();
if($access_token && $this->get_expire_time() > (time()
+ 30) || $access_token && !$this->get_expire_time()){
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
/* If we did not have a stored access token or if it
has expired, try get a new access token */
if(!$access_token){
try{
$access_token = $this->helper-
>getAccessToken();
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e-
>getMessage());
return null;
}
/* If we got a session we need to exchange it for
a long lived session. */
if(isset($access_token)){
$access_token = $this-
>long_lived_token($access_token);
$this->set_expire_time($access_token-
>getExpiresAt());
$this->set_access_token($access_token);
$this->fb-
>setDefaultAccessToken($access_token);
return $access_token;
}
}
/* Collect errors if any when using web redirect based
login */
if($this->config->item('facebook_login_type') ===
'web'){
if($this->helper->getError()){
/* Collect error data */
$error = array(
'error' => $this->helper-
>getError(),
'error_code' => $this->helper-
>getErrorCode(),
'error_reason' => $this->helper-
>getErrorReason(),
'error_description' => $this->helper-
>getErrorDescription()
);
return $error;
}
}
return $access_token;
}

/**
* Exchange short lived token for a long lived token
*
* @param AccessToken $access_token
*
* @return AccessToken|null
*/
private function long_lived_token(AccessToken
$access_token){
if(!$access_token->isLongLived()){
$oauth2_client = $this->fb->getOAuth2Client();
try{
return $oauth2_client-
>getLongLivedAccessToken($access_token);
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e-
>getMessage());
return null;
}
}
return $access_token;
}

/**
* Get stored access token
*
* @return mixed
*/
private function get_access_token(){
return $this->session->userdata('fb_access_token');
}

/**
* Store access token
*
* @param AccessToken $access_token
*/
private function set_access_token(AccessToken
$access_token){
$this->session->set_userdata('fb_access_token',
$access_token->getValue());
}

/**
* @return mixed
*/
private function get_expire_time(){
return $this->session->userdata('fb_expire');
}

/**
* @param DateTime $time
*/
private function set_expire_time(DateTime $time = null){
if ($time) {
$this->session->set_userdata('fb_expire', $time-
>getTimestamp());
}
}

/**
* @param $code
* @param $message
*
* @return array
*/
private function logError($code, $message){
log_message('error', '[FACEBOOK PHP SDK] code: ' .
$code.' | message: '.$message);
return ['error' => $code, 'message' => $message];
}

/**
* Enables the use of CI super-global without having to
define an extra variable.
*
* @param $var
*
* @return mixed
*/
public function __get($var){
return get_instance()->$var;
}
}
User_authentication.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class User_Authentication extends CI_Controller {


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

/* Load facebook oauth library */


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

/* Load user model */


$this->load->model('user');
}

public function index(){


$userData = array();

/* Authenticate user with facebook */


if($this->facebook->is_authenticated()){
/* Get user info from facebook */
$fbUser = $this->facebook->request('get',
'/me?fields=id,first_name,last_name,email,link,gender,picture'
);

/* Preparing data for database insertion */


$userData['oauth_provider'] = 'facebook';
$userData['oauth_uid'] =
!empty($fbUser['id'])?$fbUser['id']:'';;
$userData['first_name'] =
!empty($fbUser['first_name'])?$fbUser['first_name']:'';
$userData['last_name'] =
!empty($fbUser['last_name'])?$fbUser['last_name']:'';
$userData['email'] =
!empty($fbUser['email'])?$fbUser['email']:'';
$userData['gender'] =
!empty($fbUser['gender'])?$fbUser['gender']:'';
$userData['picture'] =
!empty($fbUser['picture']['data']['url'])?$fbUser['picture']['
data']['url']:'';
$userData['link'] =
!empty($fbUser['link'])?$fbUser['link']:'https://www.facebook.
com/';

/* Insert or update user data to the database */


$userID = $this->user->checkUser($userData);

/* Check user data insert or update status */


if(!empty($userID)){
$data['userData'] = $userData;

/* Store the user profile info into session */


$this->session->set_userdata('userData',
$userData);
}else{
$data['userData'] = array();
}

/* Facebook logout URL */


$data['logoutURL'] = $this->facebook-
>logout_url();
}else{
/* Facebook authentication url */
$data['authURL'] = $this->facebook->login_url();
}

/* Load login/profile view */


$this->load->view('user_authentication/index',$data);
}

public function logout() {


/* Remove local Facebook session */
$this->facebook->destroy_session();
/* Remove user data from session */
$this->session->unset_userdata('userData');
/* Redirect to login page */
redirect('user_authentication');
}
}
User.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class User extends CI_Model {


function __construct() {
$this->tableName = 'users';
$this->primaryKey = 'id';
}

/*
* Insert / Update facebook profile data into the database
* @param array the data for inserting into the table
*/
public function checkUser($userData = array()){
if(!empty($userData)){
/* check whether user data already exists in
database with same oauth info */
$this->db->select($this->primaryKey);
$this->db->from($this->tableName);
$this->db-
>where(array('oauth_provider'=>$userData['oauth_provider'],
'oauth_uid'=>$userData['oauth_uid']));
$prevQuery = $this->db->get();
$prevCheck = $prevQuery->num_rows();

if($prevCheck > 0){


$prevResult = $prevQuery->row_array();

/* update user data */


$userData['modified'] = date("Y-m-d H:i:s");
$update = $this->db->update($this->tableName,
$userData, array('id' => $prevResult['id']));

/* get user ID */
$userID = $prevResult['id'];
}else{
/* insert user data */
$userData['created'] = date("Y-m-d H:i:s");
$userData['modified'] = date("Y-m-d H:i:s");
$insert = $this->db->insert($this->tableName,
$userData);
/* get user ID */
$userID = $this->db->insert_id();
}
}

/* return user ID */
return $userID?$userID:FALSE;
}
}
user_authentication/index.php
<!-- Display login button / Facebook profile information -->
<?php if(!empty($authURL)){ ?>
<h2>CodeIgniter Facebook Login</h2>
<a href="<?php echo $authURL; ?>"><img src="<?php echo
base_url('assets/images/fb-login-btn.png'); ?>"></a>
<?php }else{ ?>
<h2>Facebook Profile Details</h2>
<div class="ac-data">
<img src="<?php echo $userData['picture']; ?>"/>
<p><b>Facebook ID:</b> <?php echo
$userData['oauth_uid']; ?></p>
<p><b>Name:</b> <?php echo $userData['first_name'].'
'.$userData['last_name']; ?></p>
<p><b>Email:</b> <?php echo $userData['email']; ?></p>
<p><b>Gender:</b> <?php echo $userData['gender'];
?></p>
<p><b>Logged in with:</b> Facebook</p>
<p><b>Profile Link:</b> <a href="<?php echo
$userData['link']; ?>" target="_blank">Click to visit Facebook
page</a></p>
<p><b>Logout from <a href="<?php echo $logoutURL;
?>">Facebook</a></p>
</div>
<?php } ?>

41. How to Login with Google Account in CodeIgniter


Sql Table
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oauth_provider` varchar(10) COLLATE utf8_unicode_ci NOT
NULL,
`oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
autoload.php
$autoload['libraries'] = array('database', 'session');

$autoload['helper'] = array('url');
google.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

/*
| ------------------------------------------------------------
-------
| Google API Configuration
| ------------------------------------------------------------
-------
|
| To get API details you have to create a Google Project
| at Google API Console
(https://console.developers.google.com)
|
| client_id string Your Google API Client ID.
| client_secret string Your Google API Client secret.
| redirect_uri string URL to redirect back to after
login.
| application_name string Your Google application name.
| api_key string Developer key.
| scopes string Specify scopes
*/
$config['google']['client_id'] =
'Google_API_Client_ID';
$config['google']['client_secret'] =
'Google_API_Client_Secret';
$config['google']['redirect_uri'] =
'https://example.com/project_folder_name/user_authentication/'
;
$config['google']['application_name'] = 'Login to
CodexWorld.com';
$config['google']['api_key'] = '';
$config['google']['scopes'] = array();
user_authentication.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class User_Authentication extends CI_Controller {

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

/* Load google oauth library */


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

/* Load user model */


$this->load->model('user');
}

public function index(){


/* Redirect to profile page if the user already
logged in */
if($this->session->userdata('loggedIn') == true){
redirect('user_authentication/profile/');
}

if(isset($_GET['code'])){

/* Authenticate user with google */


if($this->google->getAuthenticate()){

/* Get user info from google */


$gpInfo = $this->google->getUserInfo();

/* Preparing data for database insertion */


$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] =
$gpInfo['id'];
$userData['first_name'] =
$gpInfo['given_name'];
$userData['last_name'] =
$gpInfo['family_name'];
$userData['email'] =
$gpInfo['email'];
$userData['gender'] =
!empty($gpInfo['gender'])?$gpInfo['gender']:'';
$userData['locale'] =
!empty($gpInfo['locale'])?$gpInfo['locale']:'';
$userData['picture'] =
!empty($gpInfo['picture'])?$gpInfo['picture']:'';

/* Insert or update user data to the database


*/
$userID = $this->user->checkUser($userData);

/* Store the status and user profile info


into session */
$this->session->set_userdata('loggedIn',
true);
$this->session->set_userdata('userData',
$userData);
/* Redirect to profile page */
redirect('user_authentication/profile/');
}
}

/* Google authentication url */


$data['loginURL'] = $this->google->loginURL();

/* Load google login view */


$this->load->view('user_authentication/index',$data);
}

public function profile(){


/* Redirect to login page if the user not logged in
*/
if(!$this->session->userdata('loggedIn')){
redirect('/user_authentication/');
}

/* Get user info from session */


$data['userData'] = $this->session-
>userdata('userData');

/* Load user profile view */


$this->load-
>view('user_authentication/profile',$data);
}

public function logout(){


/* Reset OAuth access token */
$this->google->revokeToken();

/* Remove token and user data from the session */


$this->session->unset_userdata('loggedIn');
$this->session->unset_userdata('userData');

/* Destroy entire session data */


$this->session->sess_destroy();

/* Redirect to login page */


redirect('/user_authentication/');
}

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

class User extends CI_Model {


function __construct() {
$this->tableName = 'users';
}

public function checkUser($data = array()){


$this->db->select('id');
$this->db->from($this->tableName);

$con = array(
'oauth_provider' => $data['oauth_provider'],
'oauth_uid' => $data['oauth_uid']
);
$this->db->where($con);
$query = $this->db->get();

$check = $query->num_rows();
if($check > 0){
/* Get prev user data */
$result = $query->row_array();

/* Update user data */


$data['modified'] = date("Y-m-d H:i:s");
$update = $this->db->update($this->tableName,
$data, array('id' => $result['id']));

/* Get user ID */
$userID = $result['id'];
}else{
/* Insert user data */
$data['created'] = date("Y-m-d H:i:s");
$data['modified'] = date("Y-m-d H:i:s");
$insert = $this->db->insert($this->tableName,
$data);

/* Get user ID */
$userID = $this->db->insert_id();
}

/* Return user ID */
return $userID?$userID:false;
}

}
user_authentication/index.php
<h2>CodeIgniter Google Login</h2>
<!-- Display sign in button -->
<a href="<?php echo $loginURL; ?>"><img src="<?php echo
base_url('assets/images/google-sign-in-btn.png'); ?>" /></a>
user_authentication/profile.php
<h2>Google Account Details</h2>
<div class="ac-data">
<!-- Display Google profile information -->
<img src="<?php echo $userData['picture']; ?>"/>
<p><b>Google ID:</b> <?php echo $userData['oauth_uid'];
?></p>
<p><b>Name:</b> <?php echo $userData['first_name'].'
'.$userData['last_name']; ?></p>
<p><b>Email:</b> <?php echo $userData['email']; ?></p>
<p><b>Gender:</b> <?php echo $userData['gender']; ?></p>
<p><b>Locale:</b> <?php echo $userData['locale']; ?></p>
<p><b>Logged in with:</b> Google</p>
<p>Logout from <a href="<?php echo
base_url().'user_authentication/logout'; ?>">Google</a></p>
</div>

42. How to send Email with multiple attachment


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

/*require_once('vendor/tcpdf/examples/tcpdf_include.php');*/
class Quotation extends CI_Controller {

public function __construct()


{
parent::__construct();
if ($this->session->userdata('logged_in') != 1){
redirect('home');
}
$this->load->model('quotationmodel');
$this->load->library('form_validation');

}
public function sendmail(){
$attachmentdata = $this->quotationmodel-
>AttachmentDetailsByID($attachment_id);
$is_mail=true;
if($is_mail){
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'divyasundarsahu@gmail.com',
'smtp_pass' => 'tvrofmzfixhpynbq',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('divyasundarsahu@gmail.com',
'TNT');
$this->email->to(implode(', ', $to).','.$client_mail-
>UserEmail);
$this->email->subject($name_data['name']);
/*$this->email->isHTML(true); */
/*Quotation*/
$this->email->attach("uploads/quotation/$FileNumber-
$SlNo.pdf");

foreach($attachmentdata as $attach)
{

$this->email->attach("uploads/attachment/$attach-
>Document");
}

$email_content=$name_data['email_content'];
$email_footer=$email_signature;
$message = "$email_content
$email_footer
" ;
$this->email->message($message);
if ( ! $this->email->send()) {
show_error($this->email->print_debugger());
}
}
}
?>
Model
<?php
defined('BASEPATH') or exit('No direct script access
allowed');
date_default_timezone_set("Asia/Calcutta");
class Quotationmodel extends CI_Model
{

public function __construct()


{
parent::__construct();
$this->load->database();
}
public function AttachmentDetailsByID($attachment_id){
$query = $this->db->select("AutoID,Document");
$this->db->from('attachquotation');
$this->db->where_in('AutoID',$attachment_id);
$query = $this->db->get();
return $query->result();
}
}

43. Codeigniter import excelsheet data using


PHPSpreadSheet
upload.php
<!DOCTYPE html>
<html>
<body>

<h2>Import</h2>

<form action="Upload/import" method="POST">


<input type="file" name="file">
<input type="submit" value="Submit">
</form>

</body>
</html>
Upload.php(Controllers)
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Upload extends CI_Controller {

public function __construct()


{
$this->load->library('form_validation');
}
public function import(){
$file_mimes = array('text/x-comma-separated-values',
'text/comma-separated-values', 'application/octet-stream',
'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv',
'text/csv', 'application/csv', 'application/excel',
'application/vnd.msexcel', 'text/plain',
'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');

if(isset($_FILES['upload_file']['name']) &&
in_array($_FILES['upload_file']['type'], $file_mimes)) {
$arr_file = explode('.',
$_FILES['upload_file']['name']);
$extension = end($arr_file);
if('csv' == $extension){
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Csv();
}elseif('xls' == $extension){
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Xls();
}else {
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}
$spreadsheet = $reader-
>load($_FILES['upload_file']['tmp_name']);
$sheetData = $spreadsheet->getActiveSheet()-
>toArray();
echo "<pre>";
print_r($sheetData);

}
}
}
?>
Upload.php(with database insert)
<?php
public function import(){
$file_mimes = array('text/x-comma-separated-values',
'text/comma-separated-values', 'application/octet-stream',
'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv',
'text/csv', 'application/csv', 'application/excel',
'application/vnd.msexcel', 'text/plain',
'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');

if(isset($_FILES['upload_file']['name']) &&
in_array($_FILES['upload_file']['type'], $file_mimes)) {
$arr_file = explode('.',
$_FILES['upload_file']['name']);
$extension = end($arr_file);
if('csv' == $extension){
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Csv();
}elseif('xls' == $extension){
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Xls();
}else {
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}
$spreadsheet = $reader-
>load($_FILES['upload_file']['tmp_name']);
$sheetData = $spreadsheet->getActiveSheet()-
>toArray();
if (!empty($sheetData)) {
for ($i=1; $i<count($sheetData); $i++) {
$project_name = $sheetData[$i][0];
$file_no = $sheetData[$i][1];
$team = $sheetData[$i][2];
echo $team;
}
}

}
}
?>

44. How to Pass multiple Arrays to view in codeigniter


METHOD 1 Same variable name change key

public function index()


{
$data['data1']=$this->load_city->view();
$data['data2']=$this->load_city->spl();
$this->load->view('home_view',$data);
}
METHOD 2 Merge Your array
public function index()
{
$data['data1']=$this->load_city->view();
$data2['data2']=$this->load_city->spl();
$new_array = array_merge($data,$data2);
$this->load->view('home_view',$new_array );
}

if you want to make shortcut just add direct in method

$this->load->view('home_view',array_merge($data, $data2));

45. How to Codeigniter Select sum from database table


if (isset($options['openpos'])) {
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$query = $this->db->get();
return $query->row()->openpos;
}

46. Cron Job example codeigniter


<?php if ( ! defined('BASEPATH')) exit('No direct script
access allowed');
class Cron extends CI_Controller
{
/**
* This is default constructor of the class
*/
public function __construct()
{
parent::__construct();
$this->load->library('input');
$this->load->model('cron_model');
}

/**
* This function is used to update the age of users
automatically
* This function is called by cron job once in a day at
midnight 00:00
*/
public function updateAge()
{
/* is_cli_request() is provided by default input
library of codeigniter */
if($this->input->is_cli_request())
{
$this->cron_model->updateAge();
}
else
{
echo "You dont have access";
}
}
}
?>

Call this from your cpanel/cron manager as follows (I added more ways to
call it):

0 0 0 0 0 php-cli /home/your_site_user/public_html/index.php
cron updateAge
OR
0 0 0 0 0 wget http://your_site_url/cron/updateAge

OR

0 0 0 0 0 /usr/bin/php
/home/your_site_user/public_html/index.php cron updateAge

In my case: wget thing is working on plesk and cpanel (wget creating files on
server in your root directory). php-cli works on plesk and cpanel both.
47. How to get data in select2 using Codeigniter AJAX
Step 1 :create a table with the below sql query.

CREATE TABLE `users` (


`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 2 :Create index.php file.

Path: application/view/index.php

index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css
/select2.min.css' rel='stylesheet' type='text/css'>
<!-- Script -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery
.min.js"></script>
<script
src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/s
elect2.min.js'></script>
</head>
<body>

</body>
<script>
$(document).ready(function(){
$("#portLoading").select2({
ajax: {
url: "<?php echo base_url();?>/api/get_data.php",
type: "get",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
</script>

</body>
</html>
Step 3:Create the controller file Api.php.

Path: application/controllers/Api.php

Api.php
<?php
require APPPATH . '/libraries/TokenHandler.php';
require APPPATH . 'libraries/REST_Controller.php';
class Api extends REST_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->tokenHandler = new TokenHandler();
header('Content-Type: application/json');
}
public function port_get(){
$searchTerm=$_GET['searchTerm'];
$this->load->model('api_model');
$portdata= $this->api_model->GetPort($searchTerm);
$data = array();
foreach($portdata as $row){
$data[] = array("id"=>$row->Name, "text"=>$row-
>Name);
}
echo json_encode($data);
}
}

Step 4: Create the model file api_model.php.

application/model/api_model.php

api_model.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
class Api_model extends CI_Model {

/* constructor */
function __construct()
{
parent::__construct();
/*cache control*/
$this->output->set_header('Cache-Control: no-store,
no-cache, must-revalidate, post-check=0, pre-check=0');
$this->output->set_header('Pragma: no-cache');
}

public function GetPort($searchTerm){


$this->db->like('Name', $searchTerm);
$query = $this->db->select("PortID,Name")-
>get('PortMst');
$portlist = $query->result();
return $portlist;
}

48. Nested foreach in Codeigniter


<?php
foreach ($category as $c) {
echo "<li>" . $c->CategoryName . "</li>";
foreach ($process as $r) {
if($r['cat_id']==$c['id']){
echo "<li><a href=\"" . base_url() . "index.php/process/id/" .
$r->ProcessID . "\" target=\"_blank\">" . $r->ProcessName .
"</a></li>";
}

}
}
?>

49. How to convert a string to an int in codeigniter


Often developer face this issue when try to use a interger number in where
condition. So in this tutorial i am going to show you how to resolve this issue.

public function getblno($company_id){


$this->db->select('*');
$this->db->from('bill_of_lading');
$this->db->where('company_id',(int)$company_id);
$num_results = $this->db->count_all_results();
return $num_results;
}
50. How to update multiple row in codeigniter
There is indeed an update_batch() method available in CodeIgniter already.

You can use it your example like so:

$data = array(
array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
),
array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
)
);
$this->db->update_batch('tableName', $data, 'id');

51. How to Import and Export using PhpSpreadsheet


Library in Codeigniter
1. Download and install Codeigniter

We already discuss know about the setup of Codeigniter. If you have


any issue with the Codeigniter setup then you can check this
post Codeigniter Setup.

2. Installation of PhpSpreadsheet

To download open command prompt and run command from your


project root folder.

$ composer require phpoffice/phpspreadsheet

3. Setup Composer Autoload

application/config/config.php.$config[‘composer_autoload’] =
‘vendor/autoload.php’;

4. Creating Controller:

PhpspreadsheetController.php and use phpspreadsheet library inside


controller
PhpspreadsheetController.php
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class PhpspreadsheetController extends CI_Controller
{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('spreadsheet');
}
public function export(){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$filename = 'name-of-the-generated-file';

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.
$filename .'.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output'); /* download file */
}
public function import(){
$file_mimes = array('text/x-comma-separated-values',
'text/comma-separated-values', 'application/octet-
stream', 'application/vnd.ms-excel', 'application/x-csv',
'text/x-csv', 'text/csv', 'application/csv',
'application/excel', 'application/vnd.msexcel',
'text/plain', 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
if(isset($_FILES['upload_file']['name']) &&
in_array($_FILES['upload_file']['type'], $file_mimes)) {
$arr_file = explode('.',
$_FILES['upload_file']['name']);
$extension = end($arr_file);
if('csv' == $extension){
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
} else {
$reader = new
\PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}
$spreadsheet = $reader-
>load($_FILES['upload_file']['tmp_name']);
$sheetData = $spreadsheet->getActiveSheet()-
>toArray();
echo "<pre>";
print_r($sheetData);
}
}
}

5. Creating View:

inside application/views

spreadsheet.php
<html>
<head>
<title>Import/Export using phpspreadsheet in
codeigniter</title>
</head>
<body>
<style>
h3
{
font-family: Verdana;
font-size: 14pt;
font-style: normal;
font-weight: bold;
color:red;
text-align: center;
}

table.tr{
font-family: Verdana;
color:black;
font-size: 12pt;
font-style: normal;
font-weight: bold;
text-align:left;
}

</style>
<h3><u>Import/Export using phpspreadsheet in
codeigniter</u></h3>

<?php echo
form_open_multipart('spreadsheet/import',array('name' =>
'spreadsheet')); ?>
<table align="center" cellpadding = "5">
<tr>
<td>File :</td>
<td><input type="file" size="40px" name="upload_file"
/></td>
<td class="error"><?php echo form_error('name');
?></td>
<td colspan="5" align="center">
<input type="submit" value="Import Users"/></td>
</tr>
</table>
<?php echo form_close();?>
</body>
</html>

6. Route Configuration:

route configuration inside application/config/routes.php.

$route['spreadsheet'] = 'PhpspreadsheetController';
$route['spreadsheet/import'] =
'PhpspreadsheetController/import';
$route['spreadsheet/export'] =
'PhpspreadsheetController/export';

52. How to create multiple worksheet in phpspreadsheet


Codeigniter
?php
error_reporting(0);
defined('BASEPATH') OR exit('No direct script access
allowed');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class EDSRS extends CI_Controller {

public function __construct()


{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('ScheduleDSRmodel');
}
public function test(){
$spreadsheet = new Spreadsheet();
/* $sheet = $spreadsheet->getActiveSheet(); */
$spreadsheet->setActiveSheetIndex(0)-
>setCellValue('A1', 'Hello');
/* Rename worksheet */
$spreadsheet->getActiveSheet()->setTitle('URL Added');
$spreadsheet->createSheet();
/* Add some data */
$spreadsheet->setActiveSheetIndex(1)-
>setCellValue('A1', 'world!');
/* Rename worksheet */
$spreadsheet->getActiveSheet()->setTitle('URL
Removed');
$writer = new Xlsx($spreadsheet);
$filename=date("d-m-Y").time();
$writer-
>save("./uploads/dsr/excel/bl/$filename.xlsx");
}
}

53. How to add Unsubscribe feature in Mail Codeigniter


unsubscribe.php(Controller)
<?php
error_reporting(0);
defined('BASEPATH') OR exit('No direct script access
allowed');

class unsubscribe extends CI_Controller {


public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('magazineclientmodel');
}
public function index()
{
$this->load->view('unsubscribe');
}
public function process()
{
extract($_POST);
$data['Reason']=$reason;
$data['ChooseOption']=$option;
$data['Unsubscribe']=1;
$user=$this->magazineclientmodel-
>ManageMagazineClient($data,2,$user_id);
echo json_encode(array("statusCode"=>200));
}
}

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

class MagazineModel extends CI_Model {

public function __construct()


{
parent::__construct();
$this->load->database();
}
public function ManageMagazine($data,$type,$id=""){
if($type==1){
$this->db->insert('magazine',$data);
return $this->db->insert_id();
}
elseif($type==2){
$this->db->where('AutoID', $id);
return $this->db->update('magazine', $data);
}
elseif($type==3){
$this->db->where('AutoID', $id);
return $this->db->update('magazine', $data);
}
}
}
unsubscribe.php(View)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1, shrink-to-fit=no">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:400,700">
<title>Unsubscribe</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/b
ootstrap.min.css">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-
3.5.1.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/po
pper.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/boo
tstrap.min.js"></script>
<style>
body {
color: #fff;
background: #63738a;
font-family: 'Roboto', sans-serif;
}
.form-control {
height: 40px;
box-shadow: none;
color: #969fa4;
}
.form-control:focus {
border-color: #5cb85c;
}
.form-control, .btn {
border-radius: 3px;
}
.signup-form {
width: 550px;
margin: 0 auto;
padding: 200px 0;
font-size: 17px;
}
.signup-form h2 {
color: #636363;
margin: 0 0 15px;
position: relative;
text-align: center;
}
.signup-form h2:before, .signup-form h2:after {
content: "";
height: 2px;
width: 30%;
background: #d4d4d4;
position: absolute;
top: 50%;
z-index: 2;
}
.signup-form h2:before {
left: 0;
}
.signup-form h2:after {
right: 0;
}
.signup-form .hint-text {
color: #999;
margin-bottom: 30px;
text-align: center;
}
.signup-form form {
color: #999;
border-radius: 3px;
margin-bottom: 15px;
background: white;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
padding: 30px;
}
.signup-form .form-group {
margin-bottom: 20px;
}
.signup-form input[type="checkbox"] {
margin-top: 3px;
}
.signup-form .btn {
font-size: 16px;
font-weight: bold;
min-width: 140px;
outline: none !important;
}
.signup-form .row div:first-child {
padding-right: 10px;
}
.signup-form .row div:last-child {
padding-left: 10px;
}
.signup-form a {
color: #fff;
text-decoration: underline;
}
.signup-form a:hover {
text-decoration: none;
}
.signup-form form a {
color: #5cb85c;
text-decoration: none;
}
.signup-form form a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="signup-form">
<form action="" method="post">
<h2>Unsubscribe</h2>
<div id="mainform">
<p class="hint-text">If you have a moment, please let us know
why you unsubscribed:</p>
<div class="radio">
<label><input type="radio" name="optradio"
class="optradio" checked value="I no longer want to receive
these emails"> I no longer want to receive these
emails</label>
</div>
<div class="radio">
<label><input type="radio" name="optradio"
class="optradio" value="The emails are inappropriate"> The
emails are inappropriate</label>
</div>
<div class="radio disabled">
<label><input type="radio" name="optradio"
class="optradio" value="he emails are spam and should be
reported"> he emails are spam and should be reported</label>
</div>
<div class="radio disabled">
<label><input type="radio" name="optradio"
value="others" id="others" class="optradio"> Other (fill in
reason below)</label>
</div>
<br>

<div class="form-group" id="reason"


style="display:none;">
<label for="comment">Reason:</label>
<textarea class="form-control" rows="5"
id="comment"></textarea>
</div>
<div class="form-group">
<button type="button" class="btn btn-success btn-
lg btn-block" id="unsubscribe">Unsubscribe Now</button>
</div>
</div>
<div id="success" style="display:none;">
<p style="color:green;" align="center">Unsubscribe successful
!</p>
</div>
</form>

<script>

$(document).ready(function(){
$(".optradio").click(function(){
if($("#others").prop("checked") == true &&
$("#others").val()=='others'){
$("#reason").show();
}
else{
$("#reason").hide();
}
});
});

$("#unsubscribe").on('click',function(){
var reason = $("#comment").val();
var option = $("input:radio[name='optradio']:checked").val();
var user_id=<?php echo $_GET['user_id'];?>;
$.ajax({
url: "<?php echo base_url()?>unsubscribe/process",
type: "POST",
data: {
"reason":reason,
"option":option,
"user_id": user_id
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#mainform").hide();
$("#success").show();
}
}
});
});

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

54. How to active sidebar menu codeigniter


$this->uri->segment();

<li>
<a href="<?php echo base_url(); ?>patient/createpatient"
<?php if($this->uri->segment(1)=="menu_name"){echo
'class="active"';}?> ><i class="fa fa-users fa-lg"></i> Create
Patient </a>
</li>
<?php } ?>
<li>
<a href="<?php echo base_url(); ?>patient/listpatient"
<?php if($this->uri->segment(1)=="menu_name"){echo
'class="active"';}?> ><i class="glyphicon glyphicon-list-alt
fa-lg"> </i> List Patients </a>
</li>
<?php if( $usertype == "Admin"){?>
<li>
<a href="<?php echo base_url(); ?>user/" <?php if($this-
>uri->segment(1)=="menu_name"){echo 'class="active"';}?> ><i
class="fa fa-list fa-lg"> </i> List Users </a>
</li>

55. Codeigniter CSRF Token Example


To add CSRF token security in your Codeigniter project please follow the
below step.

Step 1:

Go to your config.php file

And Change the CSRF configuration like this.


<p>To add CSRF token security in your Codeigniter project
please follow the below step.</p>
<p><strong>Step 1:</strong></p>
<p>Go to your config.php file</p>
<p>And Change the CSRF configuration like this.</p>

Step 2:

Then in your HTML form in view file

<input type="hidden" class="txt_csrfname" name="<?= $this-


>security->get_csrf_token_name(); ?>" value="<?= $this-
>security->get_csrf_hash(); ?>">

Add the below Input box

Example:
<form id="form-validation-simple" name="form-validation-
simple" method="POST">
<input type="hidden" class="txt_csrfname" name="<?= $this-
>security->get_csrf_token_name(); ?>" value="<?= $this-
>security->get_csrf_hash(); ?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="form-label"> Topic Name <span
class="required">*</span> </label>
<input
name="Name" id="Name" value="<?php echo
$values->Name;?>" placeholder="Required, at least 4
characters" minlength="4" required
type="text"
class="form-control"
data-validation="[NOTEMPTY]"/>
</div>
</div>
</div

56. How to insert data using CodeIgniter, Ajax


register.php(View)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Register</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/boot
strap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery
.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/u
md/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootst
rap.min.js"></script>
</head>
<body>
<div class="container">
<h1 align="center">GPS Tracking</h1>
<h2>Save Data</h2>
<div class="alert alert-success alert-dismissible"
id="success" style="display:none;">
<a href="#" class="close" data-dismiss="alert" aria-
label="close">×</a>
</div>
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name"
placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email"
placeholder="Enter Email" name="email">
</div>
<div class="form-group">
<label for="email">Phone:</label>
<input type="text" class="form-control" id="phone"
placeholder="Enter Phone" name="phone">
</div>
<div class="form-group">
<label for="email">City:</label>
<input type="text" class="form-control" id="city"
placeholder="Enter City" name="city">
</div>
<button type="submit" class="btn btn-primary"
id="butsave">Submit</button>
</div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
var password = $('#password').val();
if(name!="" && email!="" && phone!="" &&
city!=""){
$("#butsave").attr("disabled", "disabled");
$.ajax({
url: "<?php echo
base_url("Crud/savedata");?>",
type: "POST",
data: {
type: 1,
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult =
JSON.parse(dataResult);
if(dataResult.statusCode==200){

$("#butsave").removeAttr("disabled");

$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data
added successfully !');
}
else
if(dataResult.statusCode==201){
alert("Error occured !");
}

}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
</body>
</html>
Crud.php(Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Crud_model');
}
public function register()
{
$this->load->view('register');
}
public function savedata()
{
if($this->input->post('type')==1)
{
$name=$this->input->post('name');
$email=$this->input->post('email');
$phone=$this->input->post('phone');
$city=$this->input->post('city');
$this->Crud_model-
>saverecords($name,$email,$phone,$city);
echo json_encode(array(
"statusCode"=>200
));
}
}
}
Crud_model.php(Model)
<?php
class Crud_model extends CI_Model
{
function saverecords($name,$email,$phone,$city)
{
$query="INSERT INTO `crud`( `name`, `email`,
`phone`, `city`)
VALUES ('$name','$email','$phone','$city')";
$this->db->query($query);
}
}

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Crud/register

Here codeIgniter is my folder name. Put your folder name instead


of codeIgniter.Rest of things are same.

57. How to Retrieve data using CodeIgniter, Ajax


We use 3 file for retrieve students data.

1. Crud.php Path: application\controllers\Crud.php


2. Crud_model.php Path: application\models\Crud_model.php
3. view.php Path: application\views\view.php

Sql Table
CREATE TABLE crud (
`id` int(11) NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
PRIMARY KEY (id)
);
view.php(View)
<!DOCTYPE html>
<html lang="en">
<head>
<title>View Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/boot
strap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery
.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/u
md/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootst
rap.min.js"></script>
</head>
<body>
<div class="container">
<h2>View data</h2>
<table class="table table-bordered table-sm" >
<thead>
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>City</th>
</tr>
</thead>
<tbody id="table">

</tbody>
</table>
</div>
<script>
$.ajax({
url: "<?php echo base_url("Crud/viewajax");?>",
type: "POST",
cache: false,
success: function(data){
//alert(data);
$('#table').html(data);
}
});
</script>
</body>
</html>

Crud.php(Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Crud_model');
}
public function view()
{
$this->load->view('view');
}

public function viewajax()


{
$data=$this->Crud_model-
>display_records();
$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-
>phone."</td>";
echo "<td>".$row-
>city."</td>";
echo "</tr>";
$i++;
}
}
}
Crud_model.php(Model)
<?php
class Crud_model extends CI_Model
{
function display_records()
{
$query=$this->db->query("select * from crud");
return $query->result();
}
}
Now run the program on your browser with the below URL:

http://localhost/codeIgniter/Crud/view
After fetch data the table look like this.

Id first name last name Email Id

1 Divyasundar Sahu divyasundar@gmail.com

2 Hritika Sahu hritika@gmail.com

3 Milan Jena milanjena@gmail.com

58. Update record using CodeIgniter, Ajax


We use 3 file for update students data.

<!DOCTYPE html>
<html lang="en">
<head>
<title>View Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/boot
strap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery
.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/u
md/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootst
rap.min.js"></script>
</head>
<body>
<div class="container">
<h2>View data</h2>
<table class="table table-bordered table-sm" >
<thead>
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table">

</tbody>
</table>
</div>
<!-- Modal Update-->
<div class="modal fade" id="update_country" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header"
style="color:#fff;background-color: #e35f14;padding:6px;">
<h5 class="modal-title"><i class="fa fa-
edit"></i> Update</h5>

</div>
<div class="modal-body">

<!--1-->
<div class="row">
<div class="col-md-3">
<label>Name</label>
</div>
<div class="col-md-9">
<input type="text"
name="name_modal" id="name_modal" class="form-control-sm"
required>
</div>
</div>
<!--2-->
<div class="row">
<div class="col-md-3">
<label>Email</label>
</div>
<div class="col-md-9">
<input type="text"
name="email_modal" id="email_modal" class="form-control-sm"
required>
</div>
</div>
<!--3-->
<div class="row">
<div class="col-md-3">
<label>Phone</label>
</div>
<div class="col-md-9">
<input type="text"
name="phone_modal" id="phone_modal" class="form-control-sm"
required>
</div>
</div>
<!--4-->
<div class="row">
<div class="col-md-3">
<label>City</label>
</div>
<div class="col-md-9">
<input type="text"
name="city_modal" id="city_modal" class="form-control-sm"
required>
</div>
</div>
<input type="hidden" name="id_modal"
id="id_modal" class="form-control-sm">
</div>
<div class="modal-footer" style="padding-
bottom:0px !important;text-align:center !important;">
<p style="text-
align:center;float:center;"><button type="submit"
id="update_data" class="btn btn-default btn-sm"
style="background-color: #e35f14;color:#fff;">Save</button>
<button type="button" class="btn btn-
default btn-sm" data-dismiss="modal" style="background-color:
#e35f14;color:#fff;">Close</button></p>

</div>
</div>
</div>
</div>
<!-- Modal End-->
<script>
$(document).ready(function() {
$.ajax({
url: "<?php echo base_url("Crud/viewajax");?>",
type: "POST",
cache: false,
success: function(dataResult){
$('#table').html(dataResult);
}
});
$(function () {
$('#update_country').on('show.bs.modal', function
(event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var name = button.data('name');
var email = button.data('email');
var phone = button.data('phone');
var city = button.data('city');
var modal = $(this);
modal.find('#name_modal').val(name);
modal.find('#email_modal').val(email);
modal.find('#phone_modal').val(phone);
modal.find('#city_modal').val(city);
modal.find('#id_modal').val(id);
});
});
$(document).on("click", "#update_data", function() {
$.ajax({
url: "<?php echo
base_url("Crud/updaterecords");?>",
type: "POST",
cache: false,
data:{
type: 3,
id: $('#id_modal').val(),
name: $('#name_modal').val(),
email: $('#email_modal').val(),
phone: $('#phone_modal').val(),
city: $('#city_modal').val()
},
success: function(dataResult){
var dataResult =
JSON.parse(dataResult);
if(dataResult.statusCode==200){

$('#update_country').modal().hide();
alert('Data updated
successfully !');
location.reload();

}
}
});
});
});
</script>
</body>
</html>
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Crud_model');
}
public function view()
{
$this->load->view('view');
}
function updaterecords()
{
if($this->input->post('type')==3)
{
$id=$this->input->post('id');
$name=$this->input->post('name');
$email=$this->input->post('email');
$phone=$this->input->post('phone');
$city=$this->input->post('city');
$this->Crud_model-
>updaterecords($id,$name,$email,$phone,$city);
echo json_encode(array(
"statusCode"=>200
));
}
}
public function viewajax()
{
$data=$this->Crud_model-
>display_records();
$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-
>phone."</td>";
echo "<td>".$row-
>city."</td>";
echo "<td><button
type='button' class='btn btn-success btn-sm update' data-
toggle='modal' data-keyboard='false' data-backdrop='static'
data-target='#update_country'
data-id=".$row->id."
data-name=".$row->name."
data-email=".$row->email."
data-phone=".$row->phone."
data-city=".$row->city."
>Edit</button></td>";
echo "</tr>";
$i++;
}
}
}
<?php
class Crud_model extends CI_Model
{
function display_records()
{
$query=$this->db->query("select * from crud");
return $query->result();
}
function updaterecords($id,$name,$email,$phone,$city)
{
$query="UPDATE `crud`
SET `name`='$name',
`email`='$email',
`phone`='$phone',
`city`='$city' WHERE id=$id";
$this->db->query($query);
}
}

59. How to delete data from database using CodeIgniter


Ajax
For delete record we use 3 file here

view.php(View)
<!DOCTYPE html>
<html lang="en">
<head>
<title>View Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/boot
strap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery
.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/u
md/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootst
rap.min.js"></script>
</head>
<body>
<div class="container">
<h2>View data</h2>
<table class="table table-bordered table-sm" >
<thead>
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table">

</tbody>
</table>
</div>
<script>
$(document).ready(function() {
$.ajax({
url: "<?php echo base_url("Crud/viewajax");?>",
type: "POST",
cache: false,
success: function(dataResult){
$('#table').html(dataResult);
}
});
$(document).on("click", ".delete", function() {
//alert("Success");
var $ele = $(this).parent().parent();
$.ajax({
url: "<?php echo
base_url("Crud/deleterecords");?>",
type: "POST",
cache: false,
data:{
type: 2,
id: $(this).attr("data-id")
},
success: function(dataResult){
alert(dataResult);
var dataResult =
JSON.parse(dataResult);
if(dataResult.statusCode==200){
$ele.fadeOut().remove();
}
}
});
});
});
</script>
</body>
</html>
Crud.php(Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Crud_model');
}

public function view()


{
$this->load->view('view');
}
function deleterecords()
{
if($this->input->post('type')==2)
{
$id=$this->input->post('id');
$this->Crud_model->deleterecords($id);
echo json_encode(array(
"statusCode"=>200
));
}
}
public function viewajax()
{
$data=$this->Crud_model-
>display_records();
$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-
>phone."</td>";
echo "<td>".$row-
>city."</td>";
echo "<td><button
type='button' class='btn btn-danger btn-sm delete' data-
id='".$row->id."'>Delete</button></td>";
echo "</tr>";
$i++;
}
}
}
Crud_model.php(Model)
<?php
class Crud_model extends CI_Model
{

function display_records()
{
$query=$this->db->query("select * from crud");
return $query->result();
}
function deleterecords($id)
{
$query="DELETE FROM `crud` WHERE id=$id";
$this->db->query($query);
}
}

60. File Upload using Codeigniter AJAX


Step 1Create a uploads folder in root directory

Step 2Create the Attachment.php(Controller) file

Step 3Create the create_attachment.php(View) File

Step 4Create the AttachmentModel.php(Model) File

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

public function __construct()


{
parent::__construct();
$this->load->model('attachmentmodel');

}
public function CreateAttachment(){
$page_data['page_title'] = 'Create Attachment';
$page_data['page_name'] =
"attachment/create_attachment";
$this->load->view('backend/index', $page_data);
}
public function ManageAttachment(){
extract($this->input->post());
$data['Title']=$Title;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload-
>display_errors());
}
else
{
$filedata = $this->upload->data();

}
$data['Logo']=$filedata['file_name'];
$data['Path']=$filedata['file_path'];
$response=$this->attachmentmodel-
>ManageAttachment($data,1);
if($response){
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-
8')
->set_output(json_encode($response));
}

}
}
create_attachment.php(View File)
<div class="form-group">
<label>Title <span class="required">*</span></label>
<input type="text" name="Title" id="Title" class="form-
control" value="<?php echo $values->Title;?>">
</div>

<label class="form-label">Upload File <span


class="required">*</span></label><br>
<input type="file" id="file" name="userfile" size="20" />
<script>
$(document).ready(function(){
jQuery(document).on('click','#submit',function(e) {
var file_data = $("#file").prop('files')[0];
var form_data = new FormData();
var Title=$("#Title").val();
var ext =
$("#file").val().split('.').pop().toLowerCase();
if ($.inArray(ext, ['png','jpg','jpeg']) == -1) {
alert("only jpg and png images allowed");
return;
}
var picsize = (file_data.size);
if(picsize > 2097152) /* 2mb*/
{
alert("Image allowd less than 2 mb")
return;
}
form_data.append('file', file_data);
form_data.append('Title',Title);
$.ajax({
url: '<?php echo
base_url()?>attachment/ManageAttachment', /*point to server-
side PHP script */
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(res){
$(".alert_success").show();
$("#success_message").text("Attachment created
successfully !");
window.location.hash = '#success_message';
window.location = `<?php eche
base_url()?>attachment`;

}
});
});
})
</script>
AttachmentModel.php(Model File)
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class AttachmentModel extends CI_Model {


public function __construct()
{
parent::__construct();
$this->load->database();

}
public function ManageAttachment($data,$type,$id=""){
if($type==1){
$this->db->insert('attachmentmst',$data);
return $this->db->insert_id();
}
}
}

You might also like