article

Showing posts with label Codeigniter. Show all posts
Showing posts with label Codeigniter. Show all posts

Wednesday, July 13, 2022

Codeigniter 4 CRUD Jquery Ajax (Create, Read, Update and Delete) with Bootstrap 5 Modal

Codeigniter 4 CRUD Jquery Ajax (Create, Read, Update and Delete) with Bootstrap 5 Modal

Download or Install Codeigniter 4

https://www.youtube.com/watch?v=YezQaWHZbis

Database table 

CREATE TABLE `students` (
  `id` int(11) NOT NULL,
  `first_name` varchar(64) NOT NULL,
  `last_name` varchar(64) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `students` (`id`, `first_name`, `last_name`, `address`) VALUES
(1, 'Cairocoders', 'Ednalan', 'Olongapo City'),
(2, 'Clydey', 'Ednalan', 'Olongapo City'),
(4, 'cairty sdf', 'Mojica sdf ', 'Olongaposdf '),
(5, 'Airi', 'Satou', 'Tokyo'),
(6, 'Angelica', 'Ramos', 'London'),
(7, 'Ashton', 'Cox', 'San Francisco'),
(8, 'Bradley', 'Greer', 'London'),
(9, 'Brenden', 'Wagner', 'San Francisco'),
(10, 'Brielle', 'Williamson', 'London'),
(11, 'Caesar', 'Vance', 'New York'),
(12, 'Cara', 'Stevens', 'New York'),
(13, 'Cedric', 'Kelly', 'Edinburgh');

ALTER TABLE `students`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `students`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
  
https://datatables.net/

DataTables is a table enhancing plug-in for the jQuery Javascript library, adding sorting, paging and filtering abilities to plain HTML tables with minimal effort.

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
setup database
app/config/database.php
//app/config/database.php
    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniterDB',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];
Create New Model
app/Models/StudentModel.php
//app/Models/StudentModel.php
<?php 
 
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
  
class StudentModel extends Model
{
    protected $table = 'Students';
  
    protected $allowedFields = ['first_name','last_name','address'];
     
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
        $builder = $db->table('Students');
    }
     
    public function insert_data($data) {
        if($this->db->table($this->table)->insert($data))
        {
            return $this->db->insertID();
        }
        else
        {
            return false;
        }
    }
}
?>
Create Controller
app/Controllers/Student.php
//app/Controllers/Student.php
<?php 
 
namespace App\Controllers;
  
use CodeIgniter\Controller;
use App\Models\StudentModel;
  
class Student extends Controller
{
  
    public function index()
    {    
        $model = new StudentModel();
  
        $data['students_detail'] = $model->orderBy('id', 'DESC')->findAll();
         
        return view('list', $data);
    }    
 
  
    public function store()
    {  
        helper(['form', 'url']);
          
        $model = new StudentModel();
         
        $data = [
            'first_name' => $this->request->getVar('txtFirstName'),
            'last_name'  => $this->request->getVar('txtLastName'),
            'address'  => $this->request->getVar('txtAddress'),
            ];
        $save = $model->insert_data($data);
        if($save != false)
        {
            $data = $model->where('id', $save)->first();
            echo json_encode(array("status" => true , 'data' => $data));
        }
        else{
            echo json_encode(array("status" => false , 'data' => $data));
        }
    }
  
    public function edit($id = null)
    {
       
     $model = new StudentModel();
     
     $data = $model->where('id', $id)->first();
      
    if($data){
            echo json_encode(array("status" => true , 'data' => $data));
        }else{
            echo json_encode(array("status" => false));
        }
    }
  
    public function update()
    {  
  
        helper(['form', 'url']);
          
        $model = new StudentModel();
 
        $id = $this->request->getVar('hdnStudentId');
 
         $data = [
            'first_name' => $this->request->getVar('txtFirstName'),
            'last_name'  => $this->request->getVar('txtLastName'),
            'address'  => $this->request->getVar('txtAddress'),
            ];
 
        $update = $model->update($id,$data);
        if($update != false)
        {
            $data = $model->where('id', $id)->first();
            echo json_encode(array("status" => true , 'data' => $data));
        }
        else{
            echo json_encode(array("status" => false , 'data' => $data));
        }
    }
  
    public function delete($id = null){
        $model = new StudentModel();
        $delete = $model->where('id', $id)->delete();
        if($delete)
        {
           echo json_encode(array("status" => true));
        }else{
           echo json_encode(array("status" => false));
        }
    }
}
 
?>
Create View
app/View/list.php
//app/View/list.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Codeigniter 4 CRUD Jquery Ajax (Create, Read, Update and Delete) with Bootstrap 5 Modal</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
</head>
<body>
<div class="container"><br/><br/>
    <div class="row">
        <div class="col-lg-10">
            <h2>Codeigniter 4 CRUD Jquery Ajax (Create, Read, Update and Delete) with Bootstrap 5 Modal</h2>
        </div>
        <div class="col-lg-2">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                Add New Student
            </button>
        </div>
    </div>

    <table class="table table-bordered table-striped" id="studentTable">
        <thead>
            <tr>
                <th>id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Address</th>
                <th width="280px">Action</th>
            </tr>
        </thead>  
        <tbody>
       <?php
        foreach($students_detail as $row){
        ?>
        <tr id="<?php echo $row['id']; ?>">
            <td><?php echo $row['id']; ?></td>
            <td><?php echo $row['first_name']; ?></td>
            <td><?php echo $row['last_name']; ?></td>
            <td><?php echo $row['address']; ?></td>
            <td>
            <a data-id="<?php echo $row['id']; ?>" class="btn btn-primary btnEdit">Edit</a>
            <a data-id="<?php echo $row['id']; ?>" class="btn btn-danger btnDelete">Delete</a>
            </td>
        </tr>
        <?php
        }
        ?>
        </tbody>
    </table>
    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ModalLabel">Add New Student</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="addStudent" name="addStudent" action="<?php echo site_url('student/store');?>" method="post">
            <div class="modal-body">
                    <div class="form-group">
                        <label for="txtFirstName">First Name:</label>
                        <input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
                    </div>
                    <div class="form-group">
                        <label for="txtLastName">Last Name:</label>
                        <input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
                    </div>
                    <div class="form-group">
                        <label for="txtAddress">Address:</label>
                        <textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
            </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ModalLabel">Update Student</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="updateStudent" name="updateStudent" action="<?php echo site_url('student/update');?>" method="post">
            <div class="modal-body">
                <input type="hidden" name="hdnStudentId" id="hdnStudentId"/>
                <div class="form-group">
                    <label for="txtFirstName">First Name:</label>
                    <input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
                </div>
                <div class="form-group">
                    <label for="txtLastName">Last Name:</label>
                    <input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
                </div>
                <div class="form-group">
                    <label for="txtAddress">Address:</label>
                    <textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
            </form>
            </div>
        </div>
    </div>

</div>

<script>
$(document).ready(function () {
    $('#studentTable').DataTable();

    $("#addStudent").validate({
        rules: {
            txtFirstName: "required",
            txtLastName: "required",
            txtAddress: "required"
        },
        messages: {
        },
          
        submitHandler: function(form) {
            var form_action = $("#addStudent").attr("action");
            $.ajax({
                data: $('#addStudent').serialize(),
                url: form_action,
                type: "POST",
                dataType: 'json',
                success: function (res) {
                    var student = '<tr id="'+res.data.id+'">';
                    student += '<td>' + res.data.id + '</td>';
                    student += '<td>' + res.data.first_name + '</td>';
                    student += '<td>' + res.data.last_name + '</td>';
                    student += '<td>' + res.data.address + '</td>';
                    student += '<td><a data-id="' + res.data.id + '" class="btn btn-primary btnEdit">Edit</a>  <a data-id="' + res.data.id + '" class="btn btn-danger btnDelete">Delete</a></td>';
                    student += '</tr>';            
                    $('#studentTable tbody').prepend(student);
                    $('#addStudent')[0].reset();
                    $('#addModal').modal('hide');
                },
                    error: function (data) {
                }
            });
        }
    });

    $('body').on('click', '.btnEdit', function () {
        var student_id = $(this).attr('data-id');
        $.ajax({
            url: 'student/edit/'+student_id,
            type: "GET",
            dataType: 'json',
            success: function (res) {
                $('#updateModal').modal('show');
                $('#updateStudent #hdnStudentId').val(res.data.id); 
                $('#updateStudent #txtFirstName').val(res.data.first_name);
                $('#updateStudent #txtLastName').val(res.data.last_name);
                $('#updateStudent #txtAddress').val(res.data.address);
            },
                error: function (data) {
            }
        });
    });
    
    $("#updateStudent").validate({
        rules: {
            txtFirstName: "required",
            txtLastName: "required",
            txtAddress: "required"
        },
            messages: {
        },
        submitHandler: function(form) {
            var form_action = $("#updateStudent").attr("action");
            $.ajax({
                data: $('#updateStudent').serialize(),
                url: form_action,
                type: "POST",
                dataType: 'json',
                success: function (res) {
                    var student = '<td>' + res.data.id + '</td>';
                    student += '<td>' + res.data.first_name + '</td>';
                    student += '<td>' + res.data.last_name + '</td>';
                    student += '<td>' + res.data.address + '</td>';
                    student += '<td><a data-id="' + res.data.id + '" class="btn btn-primary btnEdit">Edit</a>  <a data-id="' + res.data.id + '" class="btn btn-danger btnDelete">Delete</a></td>';
                    $('#studentTable tbody #'+ res.data.id).html(student);
                    $('#updateStudent')[0].reset();
                    $('#updateModal').modal('hide');
                },
                    error: function (data) {
                }
            });
        }
    }); 

    $('body').on('click', '.btnDelete', function () {
        var student_id = $(this).attr('data-id');
        $.get('student/delete/'+student_id, function (data) {
            $('#studentTable tbody #'+ student_id).remove();
        })
    });  
});   
</script>
</body>
</html>
Create Routes
app/Config/Routes.php
//app/Config/Routes.php
$routes->get('/', 'Home::index');

// CRUD Routes
$routes->get('student', 'Student::index');
$routes->post('student/store', 'Student::store');
$routes->get('student/edit/(:num)', 'Student::edit/$1');
$routes->get('student/delete/(:num)', 'Student::delete/$1');
$routes->post('student/update', 'Student::update');
Base Site URL
app/Config/App.php
public $baseURL = 'http://localhost:8080/';

Run
C:\xampp\htdocs\codeigniter4>php spark serve

http://localhost:8080/student

Tuesday, July 5, 2022

Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap

Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap

Download or Install Codeigniter 4

https://www.youtube.com/watch?v=YezQaWHZbis

Database table 
CREATE TABLE `users` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(100) NOT NULL COMMENT 'Name',
  `email` varchar(255) NOT NULL COMMENT 'Email Address'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table';

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Airi Satou', 'AiriSatou@gmail.com'),
(2, 'Angelica Ramos', 'AngelicaRamos@gmail.com'),
(3, 'Ashton Cox', 'AshtonCox@gmail.com'),
(4, 'Bradley Greer', 'BradleyGreer@gmail.com'),
(5, 'Brielle Williamson', 'BrielleWilliamson@gmail.com'),
(6, 'Bruno Nash', 'BrunoNash@gmail.com'),
(7, 'Caesar Vance', 'CaesaVance@gmail.com'),
(8, 'cairocoders', 'cairocoders@gmail.com'),
(9, 'Cara Stevens', 'CaraStevens@gmail.com'),
(11, 'caity', 'caity@gmail.com'),
(12, 'Cedric Kelly', 'CedricKelly@gmail.com');

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key', AUTO_INCREMENT=13;
  
https://datatables.net/

DataTables is a table enhancing plug-in for the jQuery Javascript library, adding sorting, paging and filtering abilities to plain HTML tables with minimal effort.

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
setup database
app/config/database.php
//app/config/database.php
    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniterDB',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];
Create New Model
app/Models/UserModel.php
//app/Models/UserModel.php
<?php 
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    
    protected $allowedFields = ['name', 'email'];
}
Create CRUD Controller
app/Controllers/UserCrud.php
//app/Controllers/UserCrud.php
<?php 
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;

class UserCrud extends Controller
{
    // users list
    public function index(){
        $userModel = new UserModel();
        $data['users'] = $userModel->orderBy('id', 'DESC')->findAll();
        return view('user_view', $data);
    }

    // user form
    public function create(){
        return view('add_user');
    }
 
    // insert data into database
    public function store() {
        $userModel = new UserModel();
        $data = [
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
        ];
        $userModel->insert($data);
        return $this->response->redirect(site_url('/users-list'));
    }

    // view single user
    public function singleUser($id = null){
        $userModel = new UserModel();
        $data['user_obj'] = $userModel->where('id', $id)->first();
        return view('edit_user', $data);
    }

    // update user data
    public function update(){
        $userModel = new UserModel();
        $id = $this->request->getVar('id');
        $data = [
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
        ];
        $userModel->update($id, $data);
        return $this->response->redirect(site_url('/users-list'));
    }
 
    // delete user
    public function delete($id = null){
        $userModel = new UserModel();
        $data['user'] = $userModel->where('id', $id)->delete($id);
        return $this->response->redirect(site_url('/users-list'));
    }    
}
Create Routes
app/Config/Routes.php
official documents here https://codeigniter4.github.io/userguide/incoming/restful.html#presenter-controller-comparison
//app/Config/Routes.php
$routes->get('/', 'Home::index');

// CRUD Routes
$routes->get('users-list', 'UserCrud::index');
$routes->get('user-form', 'UserCrud::create');
$routes->post('submit-form', 'UserCrud::store');
$routes->get('edit-view/(:num)', 'UserCrud::singleUser/$1');
$routes->post('update', 'UserCrud::update');
$routes->get('delete/(:num)', 'UserCrud::delete/$1');
Creating View
app/Views/add_user.php
//app/Views/add_user.php
<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap and Datatables</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  <style>
    .error {
      display: block;
      padding-top: 5px;
      font-size: 14px;
      color: red;
    }
  </style>
</head>
<body>
<div class="container">
	<p><h1>Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap</h1></p>
	<div class="row">
		<div class="col-2"></div>
		<div class="col-8">
			<form method="post" id="add_create" name="add_create" action="<?= site_url('/submit-form') ?>">
			  <div class="form-group">
				<label>Name</label>
				<input type="text" name="name" class="form-control">
			  </div>
			  <div class="form-group">
				<label>Email</label>
				<input type="text" name="email" class="form-control">
			  </div>
			  <div class="form-group"><br/>
				<button type="submit" class="btn btn-primary btn-block">Submit Data</button>
			  </div>
			</form>
		</div>
		<div class="col-2"></div>
	</div>
</div>
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
  <script>
    if ($("#add_create").length > 0) {
      $("#add_create").validate({
        rules: {
          name: {
            required: true,
          },
          email: {
            required: true,
            maxlength: 60,
            email: true,
          },
        },
        messages: {
          name: {
            required: "Name is required.",
          },
          email: {
            required: "Email is required.",
            email: "It does not seem to be a valid email.",
            maxlength: "The email should be or equal to 60 chars.",
          },
        },
      })
    }
  </script>
</body>
</html>
app/Views/user_view.php
//app/Views/user_view.php
<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap and Datatables</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
	<p><h1>Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap</h1></p>
    <div class="d-flex justify-content-end">
        <a href="<?php echo site_url('/user-form') ?>" class="btn btn-success mb-2">Add User</a>
	</div>
    <?php
     if(isset($_SESSION['msg'])){
        echo $_SESSION['msg'];
      }
     ?>
    <table class="table table-bordered table-striped" id="users-list">
       <thead>
          <tr>
             <th>User Id</th>
             <th>Name</th>
             <th>Email</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($users): ?>
          <?php foreach($users as $user): ?>
          <tr>
             <td><?php echo $user['id']; ?></td>
             <td><?php echo $user['name']; ?></td>
             <td><?php echo $user['email']; ?></td>
             <td>
              <a href="<?php echo base_url('edit-view/'.$user['id']);?>" class="btn btn-primary btn-sm">Edit</a>
              <a href="<?php echo base_url('delete/'.$user['id']);?>" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
    </table>
</div>
 
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script>
    $(document).ready( function () {
      $('#users-list').DataTable();
  } );
</script>
</body>
</html>
app/Views/edit_user.php
//app/Views/edit_user.php
<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap and Datatables</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  <style>
    .error {
      display: block;
      padding-top: 5px;
      font-size: 14px;
      color: red;
    }
  </style>
</head>
<body>
<div class="container">
	<p><h1>Codeigniter 4 CRUD (Create, Read, Update and Delete) with Bootstrap</h1></p>
	<div class="row">
		<div class="col-2"></div>
		<div class="col-8">
			<form method="post" id="update_user" name="update_user" action="<?= site_url('/update') ?>">
			  <input type="hidden" name="id" id="id" value="<?php echo $user_obj['id']; ?>">
			  <div class="form-group">
				<label>Name</label>
				<input type="text" name="name" class="form-control" value="<?php echo $user_obj['name']; ?>">
			  </div>

			  <div class="form-group">
				<label>Email</label>
				<input type="email" name="email" class="form-control" value="<?php echo $user_obj['email']; ?>">
			  </div>

			  <div class="form-group"> <br/>
				<button type="submit" class="btn btn-info btn-block">Save Data</button>
			  </div>
			</form>
		</div>
		<div class="col-2"></div>
	</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
<script>
    if ($("#update_user").length > 0) {
      $("#update_user").validate({
        rules: {
          name: {
            required: true,
          },
          email: {
            required: true,
            maxlength: 60,
            email: true,
          },
        },
        messages: {
          name: {
            required: "Name is required.",
          },
          email: {
            required: "Email is required.",
            email: "It does not seem to be a valid email.",
            maxlength: "The email should be or equal to 60 chars.",
          },
        },
      })
    }
  </script>
</body>
</html>
Base Site URL
app/Config/App.php
public $baseURL = 'http://localhost:8080/';

Run
C:\xampp\htdocs\codeigniter4>php spark serve

http://localhost:8080/index.php/users-list

Sunday, April 30, 2017

PayPal Payment Gateway Integration in CodeIgniter

PayPal Payment Gateway Integration in CodeIgniter

We’ll create two tables called products and payments.

Products table


CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `price` float(10,2) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

payments


CREATE TABLE `payments` (
 `payment_id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `product_id` int(11) NOT NULL,
 `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_gross` float(10,2) NOT NULL,
 `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `payer_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`payment_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller

We’ll create two controllers Products and Paypal

Products:

This controller has two methods, index(), and buy(). index()


<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller
{
    function  __construct() {
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
    }
    
    function index(){
        $data = array();
        //get products data from database
        $data['products'] = $this->product->getRows();
        //pass the products data to view
        $this->load->view('products/index', $data);
    }
    
    function buy($id){
        //Set variables for paypal form
        $returnURL = base_url().'paypal/success'; //payment success url
        $cancelURL = base_url().'paypal/cancel'; //payment cancel url
        $notifyURL = base_url().'paypal/ipn'; //ipn url
        //get particular product data
        $product = $this->product->getRows($id);
        $userID = 1; //current user id
        $logo = base_url().'assets/images/logo.png';
        
        $this->paypal_lib->add_field('return', $returnURL);
        $this->paypal_lib->add_field('cancel_return', $cancelURL);
        $this->paypal_lib->add_field('notify_url', $notifyURL);
        $this->paypal_lib->add_field('item_name', $product['name']);
        $this->paypal_lib->add_field('custom', $userID);
        $this->paypal_lib->add_field('item_number',  $product['id']);
        $this->paypal_lib->add_field('amount',  $product['price']);        
        $this->paypal_lib->image($logo);
        
        $this->paypal_lib->paypal_auto_form();
    }
}

Paypal: controller

This controller has three methods, success(), cancel(), and ipn(). success()

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paypal extends CI_Controller 
{
     function  __construct(){
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
     }
     
     function success(){
        //get the transaction data
        $paypalInfo = $this->input->get();
          
        $data['item_number'] = $paypalInfo['item_number']; 
        $data['txn_id'] = $paypalInfo["tx"];
        $data['payment_amt'] = $paypalInfo["amt"];
        $data['currency_code'] = $paypalInfo["cc"];
        $data['status'] = $paypalInfo["st"];
        
        //pass the transaction data to view
        $this->load->view('paypal/success', $data);
     }
     
     function cancel(){
        $this->load->view('paypal/cancel');
     }
     
     function ipn(){
        //paypal return transaction details array
        $paypalInfo    = $this->input->post();

        $data['user_id'] = $paypalInfo['custom'];
        $data['product_id']    = $paypalInfo["item_number"];
        $data['txn_id']    = $paypalInfo["txn_id"];
        $data['payment_gross'] = $paypalInfo["mc_gross"];
        $data['currency_code'] = $paypalInfo["mc_currency"];
        $data['payer_email'] = $paypalInfo["payer_email"];
        $data['payment_status']    = $paypalInfo["payment_status"];

        $paypalURL = $this->paypal_lib->paypal_url;        
        $result    = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
        
        //check whether the payment is verified
        if(preg_match("/VERIFIED/i",$result)){
            //insert the transaction data into the database
            $this->product->insertTransaction($data);
        }
    }
}

Model (Product) Creation

Product model has two methods, getRows() and insertTransaction(). getRows()
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Model{
    //get and return product rows
    public function getRows($id = ''){
        $this->db->select('id,name,image,price');
        $this->db->from('products');
        if($id){
            $this->db->where('id',$id);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            $this->db->order_by('name','asc');
            $query = $this->db->get();
            $result = $query->result_array();
        }
        return !empty($result)?$result:false;
    }
    //insert transaction data
    public function insertTransaction($data = array()){
        $insert = $this->db->insert('payments',$data);
        return $insert?true:false;
    }
}
View Creation

Into the views directory, we’ll create two folders called products and paypal. products/ holds the view file of the Products controller and paypal/ holds the view files of Paypal controller.

products:
This directory has only one view file (index.php). This file holds the HTML for all the products listing.
<div class="row">
    <?php if(!empty($products)): foreach($products as $product): ?>
    <div class="thumbnail">
        <img src="<?php echo base_url().'assets/images/'.$product['image']; ?>" alt="">
        <div class="caption">
            <h4 class="pull-right">$<?php echo $product['price']; ?> USD</h4>
            <h4><a href="javascript:void(0);"><?php echo $product['name']; ?></a></h4>
        </div>
        <a href="<?php echo base_url().'products/buy/'.$product['id']; ?>"><img src="<?php echo base_url(); ?>assets/images/x-click-but01.gif" style="width: 70px;"></a>
    </div>
    <?php endforeach; endif; ?>
</div>

paypal:
This directory has two view file, success.php and cancel.php.
The success.php file holds the HTML for displaying the transaction success notification.
<div>
    <h2>Dear Member</h2>
    <span>Your payment was successful, thank you for purchase.</span><br/>
    <span>Item Number : 
        <strong><?php echo $item_number; ?></strong>
    </span><br/>
    <span>TXN ID : 
        <strong><?php echo $txn_id; ?></strong>
    </span><br/>
    <span>Amount Paid : 
        <strong>$<?php echo $payment_amt.' '.$currency_code; ?></strong>
    </span><br/>
    <span>Payment Status : 
        <strong><?php echo $status; ?></strong>
    </span><br/>
</div>
The cancel.php file holds the HTML for displaying the transaction cancel notification.
<div>
    <h3>Dear Member</h3>
    <p>We are sorry! Your last transaction was cancelled.</p>
</div>

paypal_lib.php file will be placed in the application/libraries/ directory and paypallib_config.php file will be placed in the application/config/ directory.

Paypal_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 
class paypal_lib {
 var $last_error;   // holds the last error encountered
 var $ipn_log;    // bool: log IPN results to text file?
 var $ipn_log_file;   // filename of the IPN log
 var $ipn_response;   // holds the IPN response from paypal 
 var $ipn_data = array(); // array contains the POST values for IPN
 var $fields = array();  // array holds the fields to submit to paypal
 var $submit_btn = '';  // Image/Form button
 var $button_path = '';  // The path of the buttons
 
 var $CI;
 
 function __construct()
 {
  $this->CI =& get_instance();
  $this->CI->load->helper('url');
  $this->CI->load->helper('form');
  $this->CI->load->config('paypallib_config');
  
  $sanbox = $this->CI->config->item('sandbox');
  $this->paypal_url = ($sanbox == TRUE)?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';
                
  $this->last_error = '';
  $this->ipn_response = '';
  $this->ipn_log_file = $this->CI->config->item('paypal_lib_ipn_log_file');
  $this->ipn_log = $this->CI->config->item('paypal_lib_ipn_log'); 
  
  $this->button_path = $this->CI->config->item('paypal_lib_button_path');
  
  // populate $fields array with a few default values.  See the paypal
  // documentation for a list of fields and their data types. These defaul
  // values can be overwritten by the calling script.
  $businessEmail = $this->CI->config->item('business');
  $this->add_field('business',$businessEmail);
  $this->add_field('rm','2');     // Return method = POST
  $this->add_field('cmd','_xclick');
  
  $this->add_field('currency_code', $this->CI->config->item('paypal_lib_currency_code'));
      $this->add_field('quantity', '1');
  $this->button('Pay Now!');
 }
 function button($value)
 {
  // changes the default caption of the submit button
  $this->submit_btn = form_submit('pp_submit', $value);
 }
 function image($file)
 {
  $this->submit_btn = '<input type="image" name="add" src="' . site_url($this->button_path .'/'. $file) . '" border="0" />';
 }
 function add_field($field, $value) 
 {
  // adds a key=>value pair to the fields array, which is what will be 
  // sent to paypal as POST variables.  If the value is already in the 
  // array, it will be overwritten.
  $this->fields[$field] = $value;
 }
 function paypal_auto_form() 
 {
  // this function actually generates an entire HTML page consisting of
  // a form with hidden elements which is submitted to paypal via the 
  // BODY element's onLoad attribute.  We do this so that you can validate
  // any POST vars from you custom form before submitting to paypal.  So 
  // basically, you'll have your own form which is submitted to your script
  // to validate the data, which in turn calls this function to create
  // another hidden form and submit to paypal.
  $this->button('Click here if you\'re not automatically redirected...');
  echo '<html>' . "\n";
  echo '<head><title>Processing Payment...</title></head>' . "\n";
  echo '<body style="text-align:center;" onLoad="document.forms[\'paypal_auto_form\'].submit();">' . "\n";
  echo '<p style="text-align:center;">Please wait, your order is being processed and you will be redirected to the paypal website.</p>' . "\n";
  echo $this->paypal_form('paypal_auto_form');
  echo '</body></html>';
 }
 function paypal_form($form_name='paypal_form') 
 {
  $str = '';
  $str .= '<form method="post" action="'.$this->paypal_url.'" name="'.$form_name.'"/>' . "\n";
  foreach ($this->fields as $name => $value)
   $str .= form_hidden($name, $value) . "\n";
  $str .= '<p>'. $this->submit_btn . '</p>';
  $str .= form_close() . "\n";
  return $str;
 }
 
 function validate_ipn()
 {
  // parse the paypal URL
  $url_parsed = parse_url($this->paypal_url);    
  // generate the post string from the _POST vars aswell as load the
  // _POST vars into an arry so we can play with them from the calling
  // script.
  $post_string = '';  
  if ($this->CI->input->post())
  {
   foreach ($this->CI->input->post() as $field=>$value)
   { 
    $this->ipn_data[$field] = $value;
    $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; 
   }
  }
  
  $post_string.="cmd=_notify-validate"; // append ipn command
  // open the connection to paypal
  $fp = fsockopen($url_parsed['host'],"80",$err_num,$err_str,30); 
  if(!$fp)
  {
   // could not open the connection.  If loggin is on, the error message
   // will be in the log.
   $this->last_error = "fsockopen error no. $errnum: $errstr";
   $this->log_ipn_results(false);   
   return false;
  } 
  else
  { 
   // Post the data back to paypal
   fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); 
   fputs($fp, "Host: $url_parsed[host]\r\n"); 
   fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); 
   fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); 
   fputs($fp, "Connection: close\r\n\r\n"); 
   fputs($fp, $post_string . "\r\n\r\n"); 
   // loop through the response from the server and append to variable
   while(!feof($fp))
    $this->ipn_response .= fgets($fp, 1024); 
   fclose($fp); // close connection
  }
  if (preg_match("/VERIFIED/",$this->ipn_response))
  {
   // Valid IPN transaction.
   $this->log_ipn_results(true);
   return true;   
  } 
  else 
  {
   // Invalid IPN transaction.  Check the log for details.
   $this->last_error = 'IPN Validation Failed.';
   $this->log_ipn_results(false); 
   return false;
  }
 }
 function log_ipn_results($success) 
 {
  if (!$this->ipn_log) return;  // is logging turned off?
  // Timestamp
  $text = '['.date('m/d/Y g:i A').'] - '; 
  // Success or failure being logged?
  if ($success) $text .= "SUCCESS!\n";
  else $text .= 'FAIL: '.$this->last_error."\n";
  // Log the POST variables
  $text .= "IPN POST Vars from Paypal:\n";
  foreach ($this->ipn_data as $key=>$value)
   $text .= "$key=$value, ";
  // Log the response from the paypal server
  $text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response;
  // Write to log
  $fp=fopen($this->ipn_log_file,'a');
  fwrite($fp, $text . "\n\n"); 
  fclose($fp);  // close file
 }
 function dump() 
 {
  // Used for debugging, this function will output all the field/value pairs
  // that are currently defined in the instance of the class using the
  // add_field() function.
  ksort($this->fields);
  echo '<h2>ppal->dump() Output:</h2>' . "\n";
  echo '<code style="font: 12px Monaco, \'Courier New\', Verdana, Sans-serif;  background: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0; padding: 12px 10px;">' . "\n";
  foreach ($this->fields as $key => $value) echo '<strong>'. $key .'</strong>: '. urldecode($value) .'<br/>';
  echo "</code>\n";
 }
 
 
 function curlPost($paypalurl,$paypalreturnarr)
 {
  
  $req = 'cmd=_notify-validate';
  foreach($paypalreturnarr as $key => $value) 
  {
   $value = urlencode(stripslashes($value));
   $req .= "&$key=$value";
  }
   
  $ipnsiteurl=$paypalurl;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $ipnsiteurl);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
  $result = curl_exec($ch);
  curl_close($ch);
 
  return $result;
 }
}
?>
paypallib_config.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// ------------------------------------------------------------------------
// Paypal IPN Class
// ------------------------------------------------------------------------
// Use PayPal on Sandbox or Live
$config['sandbox'] = TRUE; // FALSE for live environment
// PayPal Business Email ID
$config['business'] = 'InsertPayPalBusinessEmail';
// If (and where) to log ipn to file
$config['paypal_lib_ipn_log_file'] = BASEPATH . 'logs/paypal_ipn.log';
$config['paypal_lib_ipn_log'] = TRUE;
// Where are the buttons located at 
$config['paypal_lib_button_path'] = 'buttons';
// What is the default currency?
$config['paypal_lib_currency_code'] = 'USD';
?>


Test PayPal Transaction

Open the Products controller (http://localhost/codeigniter/products)

Friday, August 12, 2016

CodeIgniter - Upload an Image

CodeIgniter - Upload an Image

Copy the following code and store it at application/view/Upload_form.php.
<html>
   <head> 
      <title>Upload Form</title> 
   </head>
   <body> 
      <?php echo $error;?> 
      <?php echo form_open_multipart('upload/do_upload');?> 
      <form action = "" method = "">
         <input type = "file" name = "userfile" size = "20" /> 
         <br /><br /> 
         <input type = "submit" value = "upload" /> 
      </form> 
   </body>
</html>

Copy the code given below and store it at application/view/upload_success.php

<html>
   <head> 
      <title>Upload Image</title> 
   </head>
   <body>  
      <h3>Upload an Image Success!</h3>  
   </body>
</html>

Copy the code given below and store it at application/controllers/upload.php. Create "uploads" folder at the root of CodeIgniter i.e. at the parent directory of application folder.

<?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']      = 100; 
         $config['max_width']     = 1024; 
         $config['max_height']    = 768;  
         $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()); 
            $this->load->view('upload_success', $data); 
         } 
      } 
   } 
?>

Make the following change in the route file in application/config/routes.php and add the following line at the end of file.

$route['upload'] = 'Upload';

Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.

http://yoursite.com/index.php/upload

Download http://bit.ly/2XgSkMN

Saturday, December 26, 2015

How to use captcha in codeigniter

How to use captcha in codeigniter

Create a controller
application/controllers/captcha.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Captcha extends CI_Controller {
   public function __construct()  {
        parent:: __construct();
  $this->load->helper("url");
  $this->load->helper('form');
  $this->load->helper('captcha');
  $this->load->library('form_validation');
    }
  public function index() {
 //validating form fields
    $this->form_validation->set_rules('username', 'Email Address', 'required');
    $this->form_validation->set_rules('user_password', 'Password', 'required');
    $this->form_validation->set_rules('userCaptcha', 'Captcha', 'required|callback_check_captcha');
    $userCaptcha = $this->input->post('userCaptcha');
 
  if ($this->form_validation->run() == false){
      // numeric random number for captcha
      $random_number = substr(number_format(time() * rand(),0,'',''),0,6);
      // setting up captcha config
      $vals = array(
             'word' => $random_number,
             'img_path' => './captcha_images/',
             'img_url' => base_url().'captcha_images/',
             'img_width' => 140,
             'img_height' => 32,
             'expiration' => 7200
            );
      $data['captcha'] = create_captcha($vals);
      $this->session->set_userdata('captchaWord',$data['captcha']['word']);
      $this->load->view('captcha', $data);
    }else {
      // do your stuff here.
      echo 'I m here clered all validations';
    }
 }
  
  public function check_captcha($str){
    $word = $this->session->userdata('captchaWord');
    if(strcmp(strtoupper($str),strtoupper($word)) == 0){
      return true;
    }
    else{
      $this->form_validation->set_message('check_captcha', 'Please enter correct words!');
      return false;
    }
 }
} 
Create folder root directory captcha_images
Create a view 
application/views/captcha.php
<html>
<head>
<title>Adding a Captcha!</title>
</head>
<body>
<h1>Captcha Example</h1>
<?php echo form_open('captcha'); ?>
<div class="formSignIn" >
  <div class="form-group">
    <input autocomplete="off" type="text" id="username" name="username" placeholder="User Email" value="<?php if(!empty($username)){ echo $username;} ?>" />
    <span class="required-server"><?php echo form_error('username','<p style="color:#F83A18">','</p>'); ?></span> </div>
  <div class="form-group">
    <input autocomplete="off" type="password" id="user_password" name="user_password" placeholder="User Password" value="" />
    <span class="required-server"><?php echo form_error('user_password','<p style="color:#F83A18">','</p>'); ?></span> </div>
  <div class="form-group">
    <label for="captcha"><?php echo $captcha['image']; ?></label>
    <br>
    <input type="text" autocomplete="off" name="userCaptcha" placeholder="Enter above text" value="<?php if(!empty($userCaptcha)){ echo $userCaptcha;} ?>" />
    <span class="required-server"><?php echo form_error('userCaptcha','<p style="color:#F83A18">','</p>'); ?></span> </div>
  <div class="form-group">
    <input type="submit" class="btn btn-success" value="Sign In" name="" />
  </div>
</div>
<?php echo form_close(); ?>
</body>
</html>

Download http://bit.ly/2Vgfjph

A Chat Example using CodeIgniter and JQuery

A Chat Example using CodeIgniter and JQuery

Controller 
chat.php
 
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Chat extends CI_Controller {
  /* The default function that gets called when visiting the page */
  public function index() {       
    $this->load->view('chat-view');
  }
  
  public function get_chats() {
    /* Connect to the mySQL database - config values can be found at:
    /application/config/database.php */
    $dbconnect = $this->load->database();
    
    /* Load the database model:
    /application/models/simple_model.php */
    $this->load->model('Chat_model');
    
    /* Create a table if it doesn't exist already */
    $this->Chat_model->create_table();
    
    echo json_encode($this->Chat_model->get_chat_after($_REQUEST["time"]));
  }
  
  public function insert_chat() {
    /* Connect to the mySQL database - config values can be found at:
    /application/config/database.php */
    $dbconnect = $this->load->database();
    
    /* Load the database model:
    /application/models/simple_model.php */
    $this->load->model('Chat_model');
    
    /* Create a table if it doesn't exist already */
    $this->Chat_model->create_table();

    $this->Chat_model->insert_message($_REQUEST["message"]); 
  }
  
  public function time() {
    echo "[{\"time\":" +  time() + "}]";
  }
  
}?>
Models 
chat_model.php
 
class Chat_model extends CI_Model {
  
  function __construct() 
  {
    /* Call the Model constructor */
    parent::__construct();
  }


  function get_last_item()
  {
    $this->db->order_by('id', 'DESC');
    $query = $this->db->get('Chats', 1);
    return $query->result();
  }
  
  
  function insert_message($message)
  {
    $this->message = $message;
    $this-> time = time();  
    $this->db->insert('Chats', $this);
  }

  function get_chat_after($time)
  {
    $this->db->where('time >', $time)->order_by('time', 'DESC')->limit(10); 
    $query = $this->db->get('Chats');
    
    $results = array();
    
    foreach ($query->result() as $row)
    {
      $results[] = array($row->message,$row->time);
    }
    
    return array_reverse($results);
  }

  function create_table()
  { 
    /* Load db_forge - used to create databases and tables */
    $this->load->dbforge();
    
    /* Specify the table schema */
    $fields = array(
                    'id' => array(
                                  'type' => 'INT',
                                  'constraint' => 5,
                                  'unsigned' => TRUE,
                                  'auto_increment' => TRUE
                              ),
                    'message' => array(
                                  'type' => 'TEXT'
                              ),
                    'time' => array(
                        'type' => 'INT'
                      )
              );
    
    /* Add the field before creating the table */
    $this->dbforge->add_field($fields);
    
    
    /* Specify the primary key to the 'id' field */
    $this->dbforge->add_key('id', TRUE);
    
    
    /* Create the table (if it doesn't already exist) */
    $this->dbforge->create_table('Chats', TRUE);
  }
}
Views 
chat-view.php
 
<html>
<head>
  <title> Chat Exmaples! </title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  <script> 
    var time = 0;
  
    var updateTime = function (cb) {
      $.getJSON("index.php/chat/time", function (data) {
          cb(~~data);
      });
    };
    
    var sendChat = function (message, cb) {
      $.getJSON("index.php/chat/insert_chat?message=" + message, function (data){
        cb();
      });
    }
    
    var addDataToReceived = function (arrayOfData) {
      arrayOfData.forEach(function (data) {
        $("#received").val($("#received").val() + "\n" + data[0]);
      });
    }
    
    var getNewChats = function () {
      $.getJSON("index.php/chat/get_chats?time=" + time, function (data){
        addDataToReceived(data);
        // reset scroll height
        setTimeout(function(){
           $('#received').scrollTop($('#received')[0].scrollHeight);
        }, 0);
        time = data[data.length-1][1];
      });      
    }
  
    // using JQUERY's ready method to know when all dom elements are rendered
    $( document ).ready ( function () {
      // set an on click on the button
      $("form").submit(function (evt) {
        evt.preventDefault();
        var data = $("#text").val();
        $("#text").val('');
        // get the time if clicked via a ajax get queury
        sendChat(data, function (){
          alert("dane");
        });
      });
      setInterval(function (){
        getNewChats(0);
      },1500);
    });
    
  </script>
</head>
<body>
  <h1> Chat Example on Codeigniter </h1>
  
  <textarea id="received" rows="10" cols="50">
  </textarea>
  <form>
    <input id="text" type="text" name="user">
    <input type="submit" value="Send">
  </form>
</body>
</html>

Saturday, November 14, 2015

Custom 404 Error messages with codeigniter

Custom 404 Error messages with codeigniter

Create controller application\controllers\My404.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class My404 extends CI_Controller
{
   public function __construct()
   {
       parent::__construct();
   }
   public function index()
   {
       $this-<output-<set_status_header('404');
       $this-<load-<view('err404');    
  }
}

Create View application\views\err404.php


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>404 Page</title>
</head>
<body>
<div>
       <p>How to Create Custom Codeigniter 404 Error Pages </p>
       <p align="center" style="font-size:55px;">Sorry Page Not Found</p>
       <p align="center" style="font-size:55px;">Error 404</p>
       <div>
           <p align="center" ><a href="<?php echo base_url(); ?>">Go Back to Home</a></p>
       </div>
</div>
</body>
</html>

add 404 to application\config\route.php $route['404_override'] = 'my404';

Sunday, February 8, 2015

Dropdown with dynamic content (Ajax/CodeIgniter)

Dropdown with dynamic content (Ajax/CodeIgniter)  

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

class Ajax_sample extends CI_Controller {
/* file: application/controllers/ajax_sample.php */

    function index(){
        $data = array();

        $data['arr_field1'] = array(
            1 => 'option 1',
            2 => 'option 2',
            3 => 'option 3',
        );

        $this->load->helper('form');

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

    function get_dropdown_values($filter){

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

        $result = $this->test_model->get_options($filter);

        $this->load->helper('form');

        echo form_dropdown('field2', $result, NULL, 'id="field2"');
    }
}
Model:
<?php
class Test_model extends CI_Model {
/* file: application/models/test_model.php */

    function get_options($filter=''){

        switch($filter){
            case 1:
                $arr = array('option A', 'option B', 'option C');
            break;
            case 2:
                $arr = array('option D', 'option E', 'option F');
            break;
            case 3:
                $arr = array('option G', 'option H', 'option I');
            break;
            default: $arr = array('option Z');
        }

        return $arr;
    }
}
View:
<?php

/* file: application/views/sample_dropdown.php */


    echo form_open('insert');

        echo form_dropdown('field1', $arr_field1, NULL, 'id="field1" onchange="load_dropdown_content($(\'#field2\'), this.value)"');

        echo form_dropdown('field2', array('0' => '...'), NULL, 'id="field2"');

    echo form_close();

?>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

function load_dropdown_content(field_dropdown, selected_value){
    var result = $.ajax({
        'url' : '<?php echo site_url('ajax_sample/get_dropdown_values'); ?>/' + selected_value,
        'async' : false
    }).responseText;
    field_dropdown.replaceWith(result);
}

</script>
URL : http://localhost/codeIgniter_3_1_10/ajax_sample

Sunday, November 23, 2014

Pagination Using Php Codeigniter

Pagination Using Php Codeigniter 

Create Database table
CREATE TABLE `country` (
  `id` smallint(5) UNSIGNED NOT NULL,
  `printable_name` varchar(255) NOT NULL,
  `CountryAbbrev` varchar(10) DEFAULT NULL,
  `CurrencyAbbr` varchar(4) DEFAULT NULL,
  `CurrencyRate` float DEFAULT NULL,
  `CurrencyCode` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
 
Codeigniter Base Url Configuration 
$config['base_url'] = "http://localhost/codeIgniter3_1_10_pagination/";
 

 
Pagination Controller (pagenation.php) application\controllers\pagenation.php

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

class Pagenation extends CI_Controller {
 public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
        $this->load->model("Countries");
        $this->load->library("pagination");
    }
 public function pagenum() 
 {
  $config = array();
        $config["base_url"] = base_url() . "pagenation/pagenum";
   $config["total_rows"] = $this->Countries->record_count();
   $config["per_page"] = 20;
  $config["uri_segment"] = 3;
  $choice = $config["total_rows"] / $config["per_page"];
  $config["num_links"] = round($choice);
     $this->pagination->initialize($config);

    $page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;
    $data["results"] = $this->Countries->fetch_countries($config["per_page"], $page);
    $data["links"] = $this->pagination->create_links();
 
    $this->load->view("expagenation", $data);

 }
}
Pagination Model (Countries.php) application\models\Countries.php
<?php
class Countries extends CI_Model
{
    public function __construct() {
        parent::__construct();
    }
  public function record_count() {
        return $this->db->count_all("country");
    }
 
 public function fetch_countries($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get("country");
  if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
      
   }


}
create expagenation.php file under folder name application/views/expagenation.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Codeigniter 3.1.10 Dev - Pagination</title>
  <link href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <h1>Countries</h1>
  <div id="body">
<?php
foreach($results as $data) {
    echo $data->printable_name . " - " . $data->CountryAbbrev . "<br>";
}
?>
   <p>
   <div class="pagination">
   <?php echo $links; ?>
   </div>
   </p>
  </div>
  <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
 </div>
  <style>
 .pagination a { 
     padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
 }
 .pagination strong{ 
     z-index: 2;
    color: #fff;
    cursor: default;
    background-color: #428bca;
    border-color: #428bca;
 padding: 6px 16px;
    margin-left: -1px;
    color: #fff;
    text-decoration: none;
 }
 </style>
</body>
</html>
Run
http://localhost/codeIgniter3_1_10_pagination/pagenation/pagenum

Download http://bit.ly/2Ey5xIu

Friday, November 21, 2014

Jquery AJAX post example with Php CodeIgniter framework

Jquery AJAX post example with Php CodeIgniter framework
<HTML>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function makeAjaxCall(){
 $.ajax({
  type: "post",
  url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
  cache: false,    
  data: $('#userForm').serialize(),
  success: function(json){      
  try{  
   var obj = jQuery.parseJSON(json);
   alert( obj['STATUS']);
     
   
  }catch(e) {  
   alert('Exception while request..');
  }  
  },
  error: function(){      
   alert('Error while request..');
  }
 });
}
</script>
</HEAD>
<BODY>
<form name="userForm" id="userForm" action="">
<table border="1">
 <tr>
  <td valign="top" align="left">  
  Username:- <input type="text" name="userName" id="userName" value="">
  </td>
 </tr>
 <tr>
  <td valign="top" align="left">  
  Password :- <input type="password" name="userPassword" id="userPassword" value="">
  </td>
 </tr>
 <tr>
  <td>
   <input type="button" onclick="javascript:makeAjaxCall();" value="Submit"/>
  </td>
 </tr>
</table>
</form>
 </BODY>
</HTML>
//UserController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserController extends CI_Controller {
 
 public function verifyUser() {
  $userName =  $_POST['userName'];
  $userPassword =  $_POST['userPassword'];
  $status = array("STATUS"=>"false");
  if($userName=='admin' && $userPassword=='admin'){
   $status = array("STATUS"=>"true"); 
  }
  echo json_encode ($status) ; 
 }
}

Thursday, May 1, 2014

PHPMailer in CodeIgniter

PHPMailer in CodeIgniter 

The first thing we do download PHPMailer library then move it to /system/application/libraries or /application/libraries/

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

class My_PHPMailer {
    public function My_PHPMailer() {
        require_once('PHPMailer/class.phpmailer.php');
    }
}
The controller
<?php
class My_Controller extends Controller {
    public function My_Controller(){
        parent::Controller();
        $this->load->library('My_PHPMailer');
    }
    public function send_mail() {
        $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   = "myusername@gmail.com";  // user email address
        $mail->Password   = "password";            // password in GMail
        $mail->SetFrom('info@yourdomain.com', 'Firstname Lastname');  //Who is sending the email
        $mail->AddReplyTo("response@yourdomain.com","Firstname Lastname");  //email address that receives the response
        $mail->Subject    = "Email subject";
        $mail->Body      = "HTML message
";
        $mail->AltBody    = "Plain text message";
        $destino = "addressee@example.com"; // Who is addressed the email to
        $mail->AddAddress($destino, "Ednalan");

        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
        if(!$mail->Send()) {
            $data["message"] = "Error: " . $mail->ErrorInfo;
        } else {
            $data["message"] = "Message sent correctly!";
        }
        $this->load->view('sent_mail',$data);
    }
}

SWFUpload in CodeIgniter

SWFUpload in CodeIgniter

What is SWFUpload?
SWFUpload is a library that allows to our website’s users to upload files to the server, using a combination of Flash and JavaScript.

Download library


The form
application/views
<?php echo form_open('process_form/process'); 
// Here we put the controller's URL and the function which will process the form?>
<div>
<?php
echo form_label('File:','file');
$data = array(  'id' => 'txtFileName',
'value' => '',
'size' => 50,
'disabled' => 'disabled',
'style' => 'border: solid 1px; background-color: #FFFFFF;');
echo form_input($data); //Insert the text field which will hold the file anem once it is uploaded
?>
<span id="spanButtonPlaceholder"></span>
(20 MB max)
</div>
<div id="fsUploadProgress"></div>
<input type="hidden" name="hidFileID" id="hidFileID" value="" />
<br />
<?php
$extra = 'id="btnSubmit"';
echo form_submit('upload','Send',$extra);
echo form_close();
?>
<!-- Add JavaScript files for SWFUpload -->
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/handlers.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/fileprogress.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend settings
upload_url: "<?php echo base_url();?>process_form/upload",
file_post_name: "resume_file",
// Flash file settings
file_size_limit : "20 MB", //File size limit
file_types : "*.jpg", // or you could use something like: "*.doc;*.wpd;*.pdf",
file_types_description : "Image Files",
file_upload_limit : 0,
file_queue_limit : 1,
// Event handler settings
swfupload_loaded_handler : swfUploadLoaded,file_dialog_start_handler: fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
//upload_start_handler : uploadStart, // I could do some client/JavaScript validation here, but I don't need to.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "<?php echo base_url();?>img/upload_flash_button_61x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,
// Flash Settings
flash_url : "<?php echo base_url();?>swf/swfupload/swfupload.swf",
flash9_url : "<?php echo base_url();?>swf/swfupload/swfupload_fp9.swf",
custom_settings : {
progress_target : "fsUploadProgress",
upload_successful : false
},
// Debug settings
debug: false
});
};
</script>
The controller
<?php
class process_form extends Controller {
public function process()
{
...
//Here we take the file's name
$file_name = $this->input->post('hidFileID');
//Once we have the file's name, we could insert into the database
//or whatever is needed
...
}

public function upload()
{
$config['upload_path'] = "path/to/the/folder/for/the/file/";
 $config['allowed_types'] = 'jpg';
 $size_mb = 20; //Max file size allowed in MB
 $config['max_size'] = $size_mb * 1024; //

 $this->load->library('upload');
 $this->upload->initialize($config);
 if (!$this->upload->do_upload('resume_file'))
 {
     $this->data["params"]["error"] = array('error_upload' => $this->upload->display_errors());
     echo $this->upload->display_errors();
 }
 else
 {
     $uploaded_file = $this->upload->data();

     //Return to the form the final name of the file once it was uploaded
     echo $uploaded_file["file_name"];
 }
}
}

Monday, March 24, 2014

How To Implement Pagination In Codeigniter ion_auth library?

How To Implement Pagination In Codeigniter ion_auth library?

Controller

function display_user()
 {
  $this->data['title'] = "Display User";

  if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
  {
   redirect('auth', 'refresh');
  }

  $this->load->library('pagination');
  $config = array();
  $config["base_url"] = base_url() . "auth/display_user/";;
  $config['total_rows'] = $this->ion_auth->users()->num_rows();
  $config['per_page'] = '30';

  //pagination customization using bootstrap styles
  $config['full_tag_open'] = ' <ul class="pagination pull-right">';
  $config['full_tag_close'] = '</ul><!--pagination-->';
  $config['first_link'] = '« First';
  $config['first_tag_open'] = '<li class="prev page">';
  $config['first_tag_close'] = '</li>';

  $config['last_link'] = 'Last »';
  $config['last_tag_open'] = '<li class="next page">';
  $config['last_tag_close'] = '</li>';

  $config['next_link'] = 'Next →';
  $config['next_tag_open'] = '<li class="next page">';
  $config['next_tag_close'] = '</li>';

  $config['prev_link'] = '← Previous';
  $config['prev_tag_open'] = '<li class="prev page">';
  $config['prev_tag_close'] = '</li>';

  $config['cur_tag_open'] = '<li class="active"><a href="">';
  $config['cur_tag_close'] = '</a></li>';

  $config['num_tag_open'] = '<li class="page">';
  $config['num_tag_close'] = '</li>';


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

  $the_uri_segment = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
  $config['uri_segment'] = $the_uri_segment;


  //list the users
  $this->data['users'] = $this->ion_auth->offset($this->uri->segment($the_uri_segment))->limit($config['per_page'])->users()->result();

  foreach ($this->data['users'] as $k => $user)
  {
   $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
  }

  $this->data['links'] = $this->pagination->create_links();
  //set the flash data error message if there is one
  $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');


  $this->data['include'] = 'auth/display_user';
  $this->_render_page('auth/template', $this->data);

 }

View

<?php echo $links;?>

How To Send Email With An Attachment In Codeigniter?

How To Send Email With An Attachment In Codeigniter?
$this->load->library('email');
$this->load->helper('path');

$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com'); 
$this->email->cc('another@another-example.com'); 
$this->email->bcc('them@their-example.com'); 

$this->email->subject('Email Test');
$this->email->message('Testing the email class.'); 

/* This function will return a server path without symbolic links or relative directory structures. */
$path = set_realpath('uploads/pdf/');
$this->email->attach($path . 'yourfile.pdf');  /* Enables you to send an attachment */


$this->email->send();

echo $this->email->print_debugger();

How To Send Email To Multiple Recipients With Attachments Using Codeigniter

How To Send Email To Multiple Recipients With Attachments Using Codeigniter 



 
//loading necessary helper classes
$this->load->library('email');
$this->load->helper('path');
$this->load->helper('directory'); 

//setting path to attach files 
$path = set_realpath('assets/your_folder/');
$file_names = directory_map($path);

foreach ($list as $name => $address)
{
    //if you set the parameter to TRUE any attachments will be cleared as well  
    $this->email->clear(TRUE);
    $this->email->to($address);
    $this->email->from('your@example.com');
    $this->email->subject('Here is your info '.$name);
    $this->email->message('Hi '.$name.' Here is the info you requested.'); 
    
    foreach($file_names as $file_name)
    {
     
      $this->email->attach($path.$file_name);
    
    }

    $this->email->send();
}

Sunday, March 23, 2014

How To Integrate Codeigniter Form Validation Library and jQuery AJAX

How To Integrate Codeigniter Form Validation Library and jQuery AJAX Controller

 
/* controller/example.php*/
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Example extends CI_Controller{

function index()
 {
  $data['include'] = 'jquery_ci_form';
  $this->load->view('template', $data);  
 }
 function jquery_save()
 {
    
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
  $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
  $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
  
  if ($this->form_validation->run() == FALSE)
  {
      
   echo json_encode(array('st'=>0, 'msg' => validation_errors()));
  }
  else
  {
   
   $username = $this->input->post('username');
   $password = $this->input->post('password');
   $email = $this->input->post('email');
   
   //...save values to database 
   
   echo json_encode(array('st'=>0, 'msg' => 'Successfully Submiited'));
  }
  
 }
}

View
 
/* view/template.php */
<?php $this->load->view('includes/header'); ?>
<?php //$this->load->view('includes/sidebar'); ?>
<?php $this->load->view($include); ?>
<?php $this->load->view('includes/footer'); ?>
/* view/jquery_ci_form.php */
<?php echo form_open('example/jquery_save', array('id'=>'frm')); ?>
<div id="validation-error"></div>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>

jQuery
 
/* assets/js/custom.js*/
$(document).ready(function() {
$('#frm').submit(function(){
 $.post($('#frm').attr('action'), $('#frm').serialize(), function( data ) {
 if(data.st == 0)
  {
   $('#validation-error').html(data.msg);
  }
    
  if(data.st == 1)
  {
    $('#validation-error').html(data.msg);
  }
    
 }, 'json');
 return false;   
   });
});

PHPMailer in CodeIgniter

PHPMailer in CodeIgniter

The first thing download the library
http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/

move folder /system/application/libraries

create a new PHP file in the CodeIgniter’s library directory called my_phpmailer.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class My_PHPMailer {
    public function My_PHPMailer() {
        require_once('PHPMailer/class.phpmailer.php');
    }
}
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Phpmailer extends CI_Controller {
 public function My_Controller(){
        parent::Controller();
        $this->load->library('My_PHPMailer');
  $this->load->library('session');
    }
  function index($msg = NULL)
 {
  $data['message'] = $msg;
  $this->load->view('contactus',$data);
 }
 public function send_mail() {
        $mail = new PHPMailer;
  //From email address and name
  $mail->From = "from@yourdomain.com";
  $mail->FromName = "Full Name";
  //To address and name
  $mail->addAddress("recepient1@example.com", "Recepient Name");
  $mail->addAddress("recepient1@example.com"); //Recipient name is optional
  //Address to which recipient will reply
  $mail->addReplyTo("reply@yourdomain.com", "Reply");
  //CC and BCC
  $mail->addCC("cc@example.com");
  $mail->addBCC("bcc@example.com");
  //Send HTML or Plain Text email
  $mail->isHTML(true);
  $mail->Subject = "Subject Text";
  $mail->Body = "<i>Mail body in HTML</i>";
  $mail->AltBody = "This is the plain text version of the email content"; 
   if(!$mail->send()) {
    $data["message"] = "Error: " . $mail->ErrorInfo;
  } else {
   $data["message"] = "<p><h3>Message sent correctly!</h3></p>";
  } 
        $this->load->view('contactus',$data);
    }
}
View
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Codeigniter 3.1.10 Dev - Phpmailer </title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Oleo+Script:400,700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Teko:400,700" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body id="page-top" class="index">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Oleo+Script:400,700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Teko:400,700" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<section id="contact">
   <div class="section-content">
    <h1 class="section-header">Get in <span class="content-header wow fadeIn " data-wow-delay="0.2s" data-wow-duration="2s"> Touch with us</span></h1>
    <h3>PHPMailer in CodeIgniter with bootstrap contact form</h3>
   </div>
   <div class="contact-section">
   <div class="container"><?php if(! is_null($message)) echo $message;?>  
    <form action="send_mail" method="post">
     <div class="col-md-6 form-line">
        <div class="form-group">
         <label for="exampleInputUsername">Your name</label>
          <input type="text" class="form-control" id="" placeholder=" Enter Name">
        </div>
        <div class="form-group">
          <label for="exampleInputEmail">Email Address</label>
          <input type="email" class="form-control" id="exampleInputEmail" placeholder=" Enter Email id">
        </div> 
        <div class="form-group">
          <label for="telephone">Mobile No.</label>
          <input type="tel" class="form-control" id="telephone" placeholder=" Enter 10-digit mobile no.">
        </div>
       </div>
       <div class="col-md-6">
        <div class="form-group">
         <label for ="description"> Message</label>
          <textarea  class="form-control" id="description" placeholder="Enter Your Message"></textarea>
        </div>
        <div>
         <button type="submit" class="btn btn-default submit"><i class="fa fa-paper-plane" aria-hidden="true"></i>  Send Message</button>
        </div>
     </div>
    </form>
   </div>
  </section>
<style>
/*Contact sectiom*/
.content-header{
  font-family: 'Oleo Script', cursive;
  color:#fcc500;
  font-size: 45px;
}
.section-content{
  text-align: center; 

}
#contact{
    font-family: 'Teko', sans-serif;
  padding-top: 60px;
  width: 100%;
  width: 100vw;
  height: 550px;
  background: #3a6186; /* fallback for old browsers */
  background: -webkit-linear-gradient(to left, #3a6186 , #89253e); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to left, #3a6186 , #89253e); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    color : #fff;    
}
.contact-section{
  padding-top: 40px;
}
.contact-section .col-md-6{
  width: 50%;
}
.form-line{
  border-right: 1px solid #B29999;
}
.form-group{
  margin-top: 10px;
}
label{
  font-size: 1.3em;
  line-height: 1em;
  font-weight: normal;
}
.form-control{
  font-size: 1.3em;
  color: #080808;
}
textarea.form-control {
    height: 135px;
   /* margin-top: px;*/
}
.submit{
  font-size: 1.1em;
  float: right;
  width: 150px;
  background-color: transparent;
  color: #fff;
}
</style>  
</body>
</html>

Related Post