Friday, 15 February 2019

Make and Download Zip File using Codeigniter



In this post, We will discuss how can we generate zip file of multiple file, after this save in folder, lastly download generated zip file by using Codeigniter framework. Codeigniter is one of the best PHP framework, which will boost you web development process and there many web developer has been used this framework for their web application development, because it is widely popular PHP framework. It has provide many built in helper and library which will help you to develop your web application very fast. This framework will helps to do many task very easily. So, here also we have one task like how to make zip file in Codeigniter framework.

Codeigniter Zip Encoding Class


If you have use Codeigniter framework, then it is very easy for you to create Zip file. Because Codeigniter has it's own built in Zip library. This class will used for generate Zip archives, and that Zip archives we can download in our local computer also. Now how to initialze this zip class. For this we have to write following code.


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


By using above code will can initialize Codeigniter Zip class, after this we can use different method of this class by calling $this->zip object. Now here we want to generate zip file of selected images from list of images. For this here we will use following method of this zip library.

read_file() - This method will read the content of a file and it will add into Zip.

add_data() - This method will add data to Zip file. In this define path of the file and data of this file.

archive() - This method will write file to the specified directory, in this method we have to define file name with complete path.

download() - This method will download created Zip file in our local computer, in this method we have to define zip file name.

Above all method of Codeigniter Zip class will help us to generate Zip file, save in folder and download in our local computer. Below you can find complete source code of this tutorial.




Make and Download Zip File using Codeigniter



Source Code


Zip_file.php(Controllers)



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

class Zip_file extends CI_Controller {
 
 function index()
 {
  $directory = 'download';
  $data["images"] = glob($directory . "/*.jpg");
  $this->load->view('zip_file', $data);
 }

 function download()
 {
  if($this->input->post('images'))
  {
   $this->load->library('zip');
   $images = $this->input->post('images');
   foreach($images as $image)
   {
    $this->zip->read_file($image);
   }
   $this->zip->download(''.time().'.zip');
  }
 }

}

?>





zip_file.php



<html>
<head>
    <title>How to Create ZIP File in CodeIgniter</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body>
 <div class="container box">
  <h3 align="center">How to Create ZIP File in CodeIgniter</h3>
  <br />
  <form method="post" action="<?php echo base_url(); ?>zip_file/download">
  <?php
  foreach($images as $image)
  {
   echo '
   <div class="col-md-2" align="center" style="margin-bottom:24px;">
    <img src="'.base_url().''.$image.'" class="img-thumbnail img-responsive" />
     <br />
    <input type="checkbox" name="images[]" class="select" value="'.$image.'" />
   </div>
   ';
  }
  ?>
  <br />
  <div align="center">
   <input type="submit" name="download" class="btn btn-primary" value="Download" />
  </div>
  </form>
 </div>
</body>
</html>

<script>
$(document).ready(function(){
 $('.select').click(function(){
  if(this.checked)
  {
   $(this).parent().css('border', '5px solid #ff0000');
  }
  else
  {
   $(this).parent().css('border', 'none');
  }
 });
});
</script>





Friday, 8 February 2019

Update or Edit Data using jQuery Dialogify with PHP Ajax



If you have use jQuery Dialogify plugin for create popup modal dialog box with your PHP web application. Then in that application you have to perform any update data operation. So, this post will help you to how to integrate jQuery Dialogify plugin for update or edit data operation using PHP with Ajax. In previous part, we have seen how can we use jquery Dialogify plugin for Insert or Add data into Mysql data using PHP with Ajax. For this things here we have use jQuery based Dialogify library for popup modal on web page. Because it is very easy to use, and it is light weight and simple plugin. For make modal dialog box, by using this plugin we have to not write any HTML code. It will allowed users to write callback function call on any event.

Here we want to update or edit data of existing mysql data using PHP script with Ajax. For load existing data into modal dialog box. If you have use this plugin, then you have to make seperate HTML form file for load data into form. Here for update or edit data, first we want to fetch existing data from database using Ajax request send to PHP. Once data has been received in json format, after this first we want to store that in Browser local storage using localStorage object, which store data with no any expiration date.

Once all data has been store in browser local storage using localStorage.setItem() method. By using this method we can store data in browser local storage. After storing all data now we have to go to seperate file in which we have create HTML form fields, and in that file, we have to fetch data from browser local storage using localStorage.getItem() method. By using this method we can fetch data from browser local storage and store into local variable. After fetching all data, after this we have to assign that data to html form fields using jquery code. Lastly we have to use new Dialogify() method, and make popup dialog box using seperate file form fields with fill data. So, when we have click on update button, then modal dialog will popup with fill form data. Lastly, we have to trigger ajax reqest when use click on Edit button, which send ajax request to PHP script for update of data. This whole process code will you can find below.




Update or Edit Data using jQuery Dialogify with PHP Ajax


Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, 'image_35.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Case', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, 'image_15.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg'),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 30, ''),
(200, 'June Barnard', '4465 Woodland Terrace Folsom, CA 95630', 'Female', 'Fishing vessel operator', 24, '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=206;


database_connection.php



<?php

//database_connection.php

$username = 'root';
$password = '';
$connect = new PDO( 'mysql:host=localhost;dbname=testing', $username, $password );

?>


index.php



<html>
 <head>
  <title>Delete Mysql Data using jQuery Dialogify with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Delete Mysql Data using jQuery Dialogify with PHP Ajax</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Employee Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_data" id="add_data" class="btn btn-success btn-xs">Add</button>
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <span id="form_response"></span>
      <table id="user_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <td>Name</td>
         <td>Gender</td>
         <td>Designation</td>
         <td>Age</td>
         <td>View</td>
         <td>Edit</td>
         <td>Delete</td>
        </tr>
       </thead>
      </table>      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 
 var dataTable = $('#user_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"fetch.php",
   type:"POST"
  },
  "columnDefs":[
   {
    "targets":[4,5,6],
    "orderable":false,
   },
  ],

 });

 $(document).on('click', '.view', function(){
  var id = $(this).attr('id');
  var options = {
   ajaxPrefix: '',
   ajaxData: {id:id},
   ajaxComplete:function(){
    this.buttons([{
     type: Dialogify.BUTTON_PRIMARY
    }]);
   }
  };
  new Dialogify('fetch_single.php', options)
   .title('View Employee Details')
   .showModal();
 });
 
 $('#add_data').click(function(){
  var options = {
   ajaxPrefix:''
  };
  new Dialogify('add_data_form.php', options)
   .title('Add New Employee Data')
   .buttons([
    {
     text:'Cancle',
     click:function(e){
      this.close();
     }
    },
    {
     text:'Insert',
     type:Dialogify.BUTTON_PRIMARY,
     click:function(e)
     {
      var image_data = $('#images').prop("files")[0];
      var form_data = new FormData();
      form_data.append('images', image_data);
      form_data.append('name', $('#name').val());
      form_data.append('address', $('#address').val());
      form_data.append('gender', $('#gender').val());
      form_data.append('designation', $('#designation').val());
      form_data.append('age', $('#age').val());
      $.ajax({
       method:"POST",
       url:'insert_data.php',
       data:form_data,
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(data)
       {
        if(data.error != '')
        {
         $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
         $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
         dataTable.ajax.reload();
        }
       }
      });
     }
    }
   ]).showModal();
 });

 $(document).on('click', '.update', function(){
  var id = $(this).attr('id');
  $.ajax({
   url:"fetch_single_data.php",
   method:"POST",
   data:{id:id},
   dataType:'json',
   success:function(data)
   {
    localStorage.setItem('name', data[0].name);
    localStorage.setItem('address', data[0].address);
    localStorage.setItem('gender', data[0].gender);
    localStorage.setItem('designation', data[0].designation);
    localStorage.setItem('age', data[0].age);
    localStorage.setItem('images', data[0].images);

    var options = {
     ajaxPrefix:''
    };
    new Dialogify('edit_data_form.php', options)
     .title('Edit Employee Data')
     .buttons([
      {
       text:'Cancle',
       click:function(e){
        this.close();
       }
      },
      {
       text:'Edit',
       type:Dialogify.BUTTON_PRIMARY,
       click:function(e)
       {
        var image_data = $('#images').prop("files")[0];
        var form_data = new FormData();
        form_data.append('images', image_data);
        form_data.append('name', $('#name').val());
        form_data.append('address', $('#address').val());
        form_data.append('gender', $('#gender').val());
        form_data.append('designation', $('#designation').val());
        form_data.append('age', $('#age').val());
        form_data.append('hidden_images', $('#hidden_images').val());
        form_data.append('id', data[0].id);
        $.ajax({
         method:"POST",
         url:'update_data.php',
         data:form_data,
         dataType:'json',
         contentType:false,
         cache:false,
         processData:false,
         success:function(data)
         {
          if(data.error != '')
          {
           $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
          }
          else
          {
           $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
           dataTable.ajax.reload();
          }
         }
        });
       }
      }
     ]).showModal();
   }
  })
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr('id');
  Dialogify.confirm("<h3 class='text-danger'><b>Are you sure you want to remove this data?</b></h3>", {
   ok:function(){
    $.ajax({
     url:"delete_data.php",
     method:"POST",
     data:{id:id},
     success:function(data)
     {
      Dialogify.alert('<h3 class="text-success text-center"><b>Data has been deleted</b></h3>');
      dataTable.ajax.reload();
     }
    })
   },
   cancel:function(){
    this.close();
   }
  });
 });
 
 
});
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');
$query = '';
$output = array();
$query .= "SELECT * FROM tbl_employee ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" OR address LIKE "%'.$_POST["search"]["value"].'%" OR gender LIKE "%'.$_POST["search"]["value"].'%" OR designation LIKE "%'.$_POST["search"]["value"].'%" OR age LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
 $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row["name"];
 $sub_array[] = $row["gender"];
 $sub_array[] = $row["designation"];
 $sub_array[] = $row["age"];
 $sub_array[] = '<button type="button" name="view" id="'.$row["id"].'" class="btn btn-primary btn-xs view">View</button>';
 $sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
 $sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
 $data[] = $sub_array;
}

function get_total_all_records($connect)
{
 $statement = $connect->prepare("SELECT * FROM tbl_employee");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  $filtered_rows,
 "recordsFiltered" => get_total_all_records($connect),
 "data"    => $data
);
echo json_encode($output);
?>


add_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
</div>


insert_data.php



<?php

//insert_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images
  );

  $query = "
  INSERT INTO tbl_employee 
  (name, address, gender, designation, age, images) 
  VALUES (:name, :address, :gender, :designation, :age, :images)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Inserted';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>







fetch_single_data.php



<?php

//fetch_single_data.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "
 SELECT * FROM tbl_employee WHERE id = '".$_POST["id"]."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}

?>


edit_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
 <span id="uploaded_image"></span>
 <input type="hidden" name="hidden_images" id="hidden_images" />
</div>

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

  var name = localStorage.getItem('name');
  var address = localStorage.getItem('address');
  var gender = localStorage.getItem('gender');
  var designation = localStorage.getItem('designation');
  var age = localStorage.getItem('age');
  var images = localStorage.getItem('images');

  $('#name').val(name);
  $('#address').val(address);
  $('#gender').val(gender);
  $('#designation').val(designation);
  $('#age').val(age);

  if(images != '')
  {
   $('#uploaded_image').html('<img src="images/'+images+'" class="img-thumbnail" width="100" />');
   $('#hidden_images').val(images);
  }

 });
</script>


update_data.php



<?php

//update_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 $images = $_POST['hidden_images'];

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images,
   ':id'   => $_POST["id"]
  );

  $query = "
  UPDATE tbl_employee 
  SET name = :name,
  address = :address,
  gender = :gender, 
  designation = :designation, 
  age = :age, 
  images = :images 
  WHERE id = :id
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Updated';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>





delete_data.php



<?php

//delete_data.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "
 DELETE FROM tbl_employee 
 WHERE id = '".$_POST["id"]."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
}

?>


Here we have provide complete source code with View data in modal dialog box, insert data, update data and delete data using jQuery Dialogify plugin using PHP with Ajax.


Tuesday, 5 February 2019

Insert or Add Data using jQuery Dialogify with PHP Ajax


This is second post on jQuery Dialogify plugin with PHP. And in this post we will discuss how to use jQuery Dialogify Plugin for insert or add data into Mysql table using PHP with Ajax. In previous post we have seen how to load dynamic mysql data into pop up dialog box using jQuery Dialogify plugin with PHP Ajax. Inserting of Data is a basic function of any application. If you want to make single page CRUD application then you have to perform all CRUD option on same page without going to another page. For do all operation on Single page you have to make form for insert data in pop up modal dialog box.

For make pop up dialog box, In one of our tutorial in which we have use Bootstrap modal for use Insert data with PHP Ajax. By using Bootstrap modal we can make pop up modal dialog box. But now we want to use jQuery Dialogify plugin for make pop up dialog box, and in this modal dialog box we want to make insert data form. Here we will not only insert data into mysql table but also we will also upload image also with data insertion. So, here we have use jquery Dialogify plugin for insert data with upload file also using PHP with Ajax. So, with jQuery Dialogify plugin we cannot make form under pop up dialog box directly.

How to make Form in jQuery Dialogify Plugin


If we have use jQuery Dialogify Plugin for insert data then for insert data we have to make form for submit data to server. But in this plugin we cannot directly make form in pop up dialog box, but for make form, we have to define form fields in some other php file. In that file we have to just define form field, this plugin will automatically add form tag. Now the question arise how other php file form will be append into jQuery Dialogify pop up modal. For this we have to write new Dialogify() method, and under this method we have to define php file in which we have define form field. This method will pop up modal dialog box with form fields, which has been define php file. Below you can find complete source code of how to use jQuery Dialogify plugin for insert or add data into mysql using PHP with Ajax.



Insert or Add Data using jQuery Dialogify with PHP Ajax




Source Code


Database



--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, 'image_35.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Case', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, 'image_15.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg'),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 30, ''),
(200, 'June Barnard', '4465 Woodland Terrace Folsom, CA 95630', 'Female', 'Fishing vessel operator', 24, '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=206;


database_connection.php



<?php

//database_connection.php

$username = 'root';
$password = '';
$connect = new PDO( 'mysql:host=localhost;dbname=testing', $username, $password );

?>



<html>
 <head>
  <title>Insert or Add Data using jQuery Dialogify with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Insert or Add Data using jQuery Dialogify with PHP Ajax</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Employee Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_data" id="add_data" class="btn btn-success btn-xs">Add</button>
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <span id="form_response"></span>
      <table id="user_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <td>Name</td>
         <td>Gender</td>
         <td>Designation</td>
         <td>Age</td>
         <td>View</td>
        </tr>
       </thead>
      </table>
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 
 var dataTable = $('#user_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"fetch.php",
   type:"POST"
  },
  "columnDefs":[
   {
    "targets":[4],
    "orderable":false,
   },
  ],

 });

 $(document).on('click', '.view', function(){
  var id = $(this).attr('id');
  var options = {
   ajaxPrefix: '',
   ajaxData: {id:id},
   ajaxComplete:function(){
    this.buttons([{
     type: Dialogify.BUTTON_PRIMARY
    }]);
   }
  };
  new Dialogify('fetch_single.php', options)
   .title('View Employee Details')
   .showModal();
 });
 
 $('#add_data').click(function(){
  var options = {
   ajaxPrefix:''
  };
  new Dialogify('add_data_form.php', options)
   .title('Add New Employee Data')
   .buttons([
    {
     text:'Cancle',
     click:function(e){
      this.close();
     }
    },
    {
     text:'Insert',
     type:Dialogify.BUTTON_PRIMARY,
     click:function(e)
     {
      var image_data = $('#images').prop("files")[0];
      var form_data = new FormData();
      form_data.append('images', image_data);
      form_data.append('name', $('#name').val());
      form_data.append('address', $('#address').val());
      form_data.append('gender', $('#gender').val());
      form_data.append('designation', $('#designation').val());
      form_data.append('age', $('#age').val());
      $.ajax({
       method:"POST",
       url:'insert_data.php',
       data:form_data,
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(data)
       {
        if(data.error != '')
        {
         $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
         $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
         dataTable.ajax.reload();
        }
       }
      });
     }
    }
   ]).showModal();
 });
 
 
});
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');
$query = '';
$output = array();
$query .= "SELECT * FROM tbl_employee ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" OR address LIKE "%'.$_POST["search"]["value"].'%" OR gender LIKE "%'.$_POST["search"]["value"].'%" OR designation LIKE "%'.$_POST["search"]["value"].'%" OR age LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
 $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row["name"];
 $sub_array[] = $row["gender"];
 $sub_array[] = $row["designation"];
 $sub_array[] = $row["age"];
 $sub_array[] = '<button type="button" name="view" id="'.$row["id"].'" class="btn btn-primary btn-xs view">View</button>';
 $data[] = $sub_array;
}

function get_total_all_records($connect)
{
 $statement = $connect->prepare("SELECT * FROM tbl_employee");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  $filtered_rows,
 "recordsFiltered" => get_total_all_records($connect),
 "data"    => $data
);
echo json_encode($output);
?>


fetch_single.php



<?php

//fetch_single.php

include('database_connection.php');

if(isset($_GET["id"]))
{
 $query = "SELECT * FROM tbl_employee WHERE id = '".$_GET["id"]."'";

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<div class="row">';
 foreach($result as $row)
 {
  $images = '';
  if($row["images"] != '')
  {
   $images = '<img src="images/'.$row["images"].'" class="img-responsive img-thumbnail" />';
  }
  else
  {
   $images = '<img src="https://www.gravatar.com/avatar/38ed5967302ec60ff4417826c24feef6?s=80&d=mm&r=g" class="img-responsive img-thumbnail" />';
  }
  $output .= '
  <div class="col-md-3">
   <br />
   '.$images.'
  </div>
  <div class="col-md-9">
   <br />
   <p><label>Name :&nbsp;</label>'.$row["name"].'</p>
   <p><label>Address :&nbsp;</label>'.$row["address"].'</p>
   <p><label>Gender :&nbsp;</label>'.$row["gender"].'</p>
   <p><label>Designation :&nbsp;</label>'.$row["designation"].'</p>
   <p><label>Age :&nbsp;</label>'.$row["age"].' years</p>
  </div>
  </div><br />
  ';
 }
 echo $output;
}

?>







add_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
</div>


insert_data.php



<?php

//insert_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images
  );

  $query = "
  INSERT INTO tbl_employee 
  (name, address, gender, designation, age, images) 
  VALUES (:name, :address, :gender, :designation, :age, :images)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Inserted';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>


This is combine source code of View Dyanmic Data using Dialogify plugin post and Insert Data using Dialogify with PHP Ajax. If you have any query regarding this post, you can send your query via comment.

Wednesday, 30 January 2019

Ajax PHP - Load Data in Modal with Dialogify Plugin



If you are looking for web tutorial on Loading of Dynamic Ajax content in Modal dialog box using PHP script, then tutorial will help you to learn how to load dynamic content in modal dialog box with PHP script. Because in this post we have do something like this. Here we have load mysql dynamic data in modal dialog box by using jQuery Dialogify plugin with Ajax and PHP. Jquery Dialogify plugin is used for make modern stylish modal dialog box, and this plugin we can use different purpose like pop up of message on web page, it can be used in place javascript confirm dialog and it can also be used as in place of javascript prompt dialog box also. By using this jQuery Dialogify modal dialog box we can also perform form submission operation also. But here we have use this plugin for load dyamic data into this modal dialog box.

This plugin we can also use in place of Bootstrap modal box, because in bootstrap modal dialog box, we have to write html code for it. But with jQuery Dialogify plugin we have not write any html code for make modal dialog box. But we have to write only some javascript code only. We have already publish tutorial on how to load dynamic data in Bootstrap modal using Ajax PHP. But this plugin also we can use for make different type of dialog box as per our requirement.

For initialize this plugin we have to just write new Dialogify() method, this method will initialize this plugin, here we have use this plugin with ajax, so in this this new Dialogify() method we have to add php script file, so when this plugin has been initialize then it will send request to php script for fetch data from mysql table. In second argument of new Dialogify() method we have to define different option like which data we want send with Ajax request, button property of modal dialog box etc. After define this things, now we want to set modal header title, for this we can use title() method, this method is used for set header title of modal dialog box. And lastly we have to write .showModal() method, this method will pop up Dialogify modal dialog box on web page with dynamic data. Below you can find complete source code of Loading of Dynamic content in Modal dialog box using jQuery Dialogify plugin with Ajax jquery.


Ajax PHP - Load Data in Modal with Dialogify Plugin




Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, 'image_35.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Case', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, 'image_15.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg'),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 30, ''),
(200, 'June Barnard', '4465 Woodland Terrace Folsom, CA 95630', 'Female', 'Fishing vessel operator', 24, '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=206;


database_connection.php



<?php

//database_connection.php

$username = 'root';
$password = '';
$connect = new PDO( 'mysql:host=localhost;dbname=testing', $username, $password );

?>


index.php



<html>
 <head>
  <title>View Dynamic Data using jQuery Dialogify with Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">View Dynamic Data using jQuery Dialogify with Ajax PHP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Employee Data</h3>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <table id="user_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <td>Name</td>
         <td>Gender</td>
         <td>Designation</td>
         <td>Age</td>
         <td>View</td>
        </tr>
       </thead>
      </table>
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 
 var dataTable = $('#user_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"fetch.php",
   type:"POST"
  },
  "columnDefs":[
   {
    "targets":[4],
    "orderable":false,
   },
  ],

 });

 $(document).on('click', '.view', function(){
  var id = $(this).attr('id');
  var options = {
   ajaxPrefix: '',
   ajaxData: {id:id},
   ajaxComplete:function(){
    this.buttons([{
     type: Dialogify.BUTTON_PRIMARY
    }]);
   }
  };
  new Dialogify('fetch_single.php', options)
   .title('View Employee Details')
   .showModal();
 });
 
 
 
 
});
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');
$query = '';
$output = array();
$query .= "SELECT * FROM tbl_employee ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" OR address LIKE "%'.$_POST["search"]["value"].'%" OR gender LIKE "%'.$_POST["search"]["value"].'%" OR designation LIKE "%'.$_POST["search"]["value"].'%" OR age LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
 $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row["name"];
 $sub_array[] = $row["gender"];
 $sub_array[] = $row["designation"];
 $sub_array[] = $row["age"];
 $sub_array[] = '<button type="button" name="view" id="'.$row["id"].'" class="btn btn-primary btn-xs view">View</button>';
 $data[] = $sub_array;
}

function get_total_all_records($connect)
{
 $statement = $connect->prepare("SELECT * FROM tbl_employee");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  $filtered_rows,
 "recordsFiltered" => get_total_all_records($connect),
 "data"    => $data
);
echo json_encode($output);
?>







fetch_single.php



<?php

//fetch_single.php

include('database_connection.php');

if(isset($_GET["id"]))
{
 $query = "SELECT * FROM tbl_employee WHERE id = '".$_GET["id"]."'";

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<div class="row">';
 foreach($result as $row)
 {
  $images = '';
  if($row["images"] != '')
  {
   $images = '<img src="images/'.$row["images"].'" class="img-responsive img-thumbnail" />';
  }
  else
  {
   $images = '<img src="https://www.gravatar.com/avatar/38ed5967302ec60ff4417826c24feef6?s=80&d=mm&r=g" class="img-responsive img-thumbnail" />';
  }
  $output .= '
  <div class="col-md-3">
   <br />
   '.$images.'
  </div>
  <div class="col-md-9">
   <br />
   <p><label>Name :&nbsp;</label>'.$row["name"].'</p>
   <p><label>Address :&nbsp;</label>'.$row["address"].'</p>
   <p><label>Gender :&nbsp;</label>'.$row["gender"].'</p>
   <p><label>Designation :&nbsp;</label>'.$row["designation"].'</p>
   <p><label>Age :&nbsp;</label>'.$row["age"].' years</p>
  </div>
  </div><br />
  ';
 }
 echo $output;
}

?>


Above source code is a complete source with load data into jQuery Datatables plugin and view dynamic mysql data into jQuery Dialogigy plugin modal dialog box using Ajax PHP.

Monday, 28 January 2019

Uploading Image in CKEDITOR with PHP



If you have build any content management system or any other system in which you have use CKEDITOR HTML editor. So, Now you want to upload Image from CKEDITOR using PHP script. For this here we have make this post, in which we have step by step describe how to make custom image upload in CKEDITOR from your PHP application. We all know CKEDITOR is a widely used HTML editor in any web based application, and it is very easy to use, and it is very easy to integrate in our application.

Suppose you have used CKEDITOR in your web application, then by default for add image into your content, you have to just add upload image path into image dialog box and you can adjust property of image. But you cannot direct upload image from your local computer into text editor. For upload image or file in CKEDITOR, there are two way you can upload image in CKEDITOR, first you have to use any plugin for upload image in CKEDITOR or you have to make custom image upload in CKEDITOR.

Here we have discuss, how to make custom image upload in CKEDITOR using PHP script. For make custom image upload in CKEDITOR, you have to follow following steps.

1 - Integrate CKEDITOR
2 - Create HTML code file for integrate CKEDITOR
3 - Make PHP script for upload Image






1 - Integrate CKEDITOR


If you want to use CKEDITOR into your PHP web application, then first you have to download CKEDITOR from it's official site or even you can directly use cdn for CKEDITOR for it's official site also.

Create HTML code file for integrate CKEDITOR


Suppose you have done download CKEDITOR or use cdn of CKEDITOR in your application, For this here we have make index.php file. In this file we have make simple html code of textarea field. Below you can check how to integrate CKEDITOR in textarea html field and after integrate CKEDITOR it will convert into textarea field. In this HTML code we have use cdn of CKEDITOR for integrate into our application.

In this code textarea field class=ckeditor is used as selector for integrate CKEDITOR on this textarea field. For enable upload tab, you can see in javascript code, in which we have use filebrowserUploadUrl option. This option will enable upload tab in CKEDITOR image dialog box. In this option we can define PHP script file name, this PHP script will upload selected image into folder. That means this option will send request this file for upload image. This complete source code you can find below.


<!DOCTYPE html>
<html>
 <head>
  <title>How to Upload Image using ckeditor in PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="http://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">How to Upload Image using ckeditor in PHP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">How to Upload Image using ckeditor in PHP</h3>
    </div>
    <div class="panel-body">
     <textarea name="content" id="content" class="form-control ckeditor"></textarea>
    </div>
   </div>
  </div>
 </body>
</html>

<script>
 CKEDITOR.replace( 'content', {
  height: 300,
  filebrowserUploadUrl: "upload.php"
 });
</script>


3 - Make PHP script for upload Image


Once you have done integrate CKEDITOR into HTML code, and enable upload tab in image dialog box. Now you have to make PHP script for upload selected image from local computer to upload folder and send uploaded image request back to CKEDITOR image dialog box. For this source code you can find below.






upload.php

<?php

//upload.php

if(isset($_FILES['upload']['name']))
{
 $file = $_FILES['upload']['tmp_name'];
 $file_name = $_FILES['upload']['name'];
 $file_name_array = explode(".", $file_name);
 $extension = end($file_name_array);
 $new_image_name = rand() . '.' . $extension;
 chmod('upload', 0777);
 $allowed_extension = array("jpg", "gif", "png");
 if(in_array($extension, $allowed_extension))
 {
  move_uploaded_file($file, 'upload/' . $new_image_name);
  $function_number = $_GET['CKEditorFuncNum'];
  $url = 'upload/' . $new_image_name;
  $message = '';
  echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($function_number, '$url', '$message');</script>";
 }
}

?>


This is complete step by step process for how to integrate CKEDITOR in PHP application, how to enable upload tab in CKEDITOR image dialog box and how to upload image in CKEDITOR using PHP script.

Wednesday, 23 January 2019

Codeigniter Export Mysql Data to CSV File



If you looking for web tutorial on exporting mysql data to CSV file in Codeignier. So, you have come on right place, in this post we have covered topic like export mysql data to CSV file in Codeigniter framework. Every body knows Codeigniter framework is used for boost you coding for make faster web based application. Once application has been make perfectly and end use your application completely, then you web application has large amount of data. Then at that time you have store that in readable file format. At that time you have to export your web application data in CSV (Comma-Seperated Values) file format. Because data inthis file format is widly used for importing and exporting data in web based application. And CSV file format is lightweight for store data in spread format.

Now question is arise How could you export mysql data in CSV file and download data in CSV file from live application in Codeigniter. First of all, we have already publish tutorial on how to import data from CSV file in Codeigniter framework. Now, In this post, we will discuss how to export data from Mysql database into CSV file using Codeigniter. Here also you can learn how to create CSV file in Codeigniter and download into local computer or Save Mysql data into CSV file in Codeigniter.

For describe Mysql data export to CSV file feature, we have make script in Codeigniter MVC framework, in which export student data from Mysql database table and insert into CSV file using Codeigniter.





Make Table in Mysql Database


Below script will make student table in your Mysql database. You have to run follow script in your PHPMyAdmin.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_student`
--

CREATE TABLE `tbl_student` (
  `student_id` int(11) NOT NULL,
  `student_name` varchar(250) NOT NULL,
  `student_phone` varchar(20) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_student`
--
ALTER TABLE `tbl_student`
  ADD PRIMARY KEY (`student_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_student`
--
ALTER TABLE `tbl_student`
  MODIFY `student_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;





Make Database Connection in Codeigniter


Once student table has been ready, then you have to make database connection in Codeigniter, for database connection in Codeigniter, you have to go to application/config/database.php. In this file you have make database connection in Codeigniter.

application/config/database.php

<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 '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
);

?>





Export_csv.php (Controllers)


After making database connection, you have to create Export_csv.php file in application/controllers folder. Controllers files mainly used for handle HTTP request of application. In this file we have to make follow method.

index() - This method is a root method of this class, this method will received student data from model and send data to view file.
export() - This method is received form submission request for export mysql data to CSV file. This function will write mysql data under CSV file and after file send for download.

application/controllers/Export_csv.php

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

class Export_csv extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('export_csv_model');
 }

 function index()
 {
  $data['student_data'] = $this->export_csv_model->fetch_data();
  $this->load->view('export_csv', $data);
 }

 function export()
 {
  $file_name = 'student_details_on_'.date('Ymd').'.csv'; 
     header("Content-Description: File Transfer"); 
     header("Content-Disposition: attachment; filename=$file_name"); 
     header("Content-Type: application/csv;");
   
     // get data 
     $student_data = $this->export_csv_model->fetch_data();

     // file creation 
     $file = fopen('php://output', 'w');
 
     $header = array("Student Name","Student Phone"); 
     fputcsv($file, $header);
     foreach ($student_data->result_array() as $key => $value)
     { 
       fputcsv($file, $value); 
     }
     fclose($file); 
     exit; 
 }
 
  
}



Export_csv_model.php (Models)


Models files in Codeigniter mainly used for database operation. You have to create models file in application/models folder. In this file there is only one method we have make. Here fetch_data() method is used for fetch data from student table.


<?php
class Export_csv_model extends CI_Model
{
 function fetch_data()
 {
  $this->db->select("student_name, student_phone");
  $this->db->from('tbl_student');
  return $this->db->get();
 }
}

?>



export_csv.php (Views)


This view file is used for display output in HTML format on web page. This file you have to make in application/views folder. This file first received student data from controllers, and when used click on export button, then it has received data export to CSV request for export data to CSV file.


<html>
<head>
    <title>How to Export Mysql Data to CSV File in Codeigniter</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body>
 <div class="container box">
  <h3 align="center">How to Export Mysql Data to CSV File in Codeigniter</h3>
  <br />
  <form method="post" action="<?php echo base_url(); ?>export_csv/export">
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Student Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <input type="submit" name="export" class="btn btn-success btn-xs" value="Export to CSV" />
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <table class="table table-bordered table-striped">
       <tr>
        <th>Student Name</th>
        <th>Student Phone</th>
       </tr>
       <?php
       foreach($student_data->result_array() as $row)
       {
        echo '
        <tr>
         <td>'.$row["student_name"].'</td>
         <td>'.$row["student_phone"].'</td>
        </tr>
        ';
       }
       ?>
      </table>
     </div>
    </div>
   </div>
  </form>
 </div>
</body>
</html>


This tutorial will you help to learn exporting of Mysql Data to CSV file format in Codeigniter.

Monday, 7 January 2019

Twitter Like Follow Unfollow System in PHP using Ajax jQuery



From this post, you can learn how to make Follow and Unfollow system like Twitter which you can create in PHP using Ajax jQuery Mysql and Bootstrap. There are many viewers has requested to use PHP to build a Twitter like system. If you know on Twitter can post short News in Tweets format, and that tweets will be visible to those Twitter user who has follow this share user. When user share any news or tweets, that will be visible to his followers. So, this type of system we will make in PHP using Ajax jQuery and Mysql Database.

IF you are looking for any Social Networking Application for you colleage project, Then this post will help you to make small Follow Unfollow Application in PHP using Ajax step by step. On every publish of video tutorial of this post, you can find updated source code under this post. So, here we will show you How to develop twitter like follow and Unfollow system using Ajax in PHP script. Because most of this Social Networking sites are make in PHP Ajax. Here we have also use Bootstrap library for CSS purpose for make this system. So, here we will make dynamic follow unfollow application in PHP using Ajax.

Following are the main functionality of this follow unfollow system.

  • New User Registration
  • Login form for registered user
  • Authenticated User can edit his or here profile with upload profile image
  • User can share post, and list post
  • List User with follow unfollow button
  • Display number of followers of each user
  • Main functionality is to follow or unfollow other user post
  • Display dynamic results will be display if user click on follow unfollo button
  • All data will display using Ajax without refresh of web page
  • If you user follow any user, then he can also unfollow that user again

So, Above are the main functionality of this follow unfollow system in PHP using Ajax jQuery Mysql and Bootstrap. Below you can find source code of Ajax based follow unfollow system.



Video Tutorial


Part 1




Part 2




Part 3




Part 4




Part 5




Part 6




Part 7




Part 8




Part 9




Part 10




Source Code


Database


Run follow SQL script, it will make three table like tbl_twitter_user, tbl_samples_post and tbl_follow in your PHPMysqmin. Follow Unfollow system has been use this three table for make application.


CREATE TABLE `tbl_follow` (
  `follow_id` int(11) NOT NULL AUTO_INCREMENT,
  `sender_id` int(11) NOT NULL,
  `receiver_id` int(11) NOT NULL,
  PRIMARY KEY (`follow_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_samples_post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `post_content` text NOT NULL,
  `post_datetime` datetime NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_twitter_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `name` varchar(150) NOT NULL,
  `profile_image` varchar(150) NOT NULL,
  `bio` text NOT NULL,
  `follower_number` int(11) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_comment` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `comment` text NOT NULL,
  `timestamp` datetime NOT NULL,
  PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;



database_connection.php


This PHP file is used for make database connection. This is common file which we will used in all files for make Mysql Database connection.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>







register.php


For any dynamic web application, we have to first make register form. So, here also first we want to make user registration system. So, new user can register into system. So, for make any dynamic system, here we have make this register form. In this system, here we have validate username already exists or not. If username already exists then user cannot register into system. In this registration system we have also validate user password by re-entering password. So, this is basic validation, which we have use here for make registration system for Follow Unfollow system using PHP with Ajax jQuery Mysql and Bootstrap.


<!--
//register.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST['register']))
{
 $username = trim($_POST["username"]);
 $password = trim($_POST["password"]);
 $check_query = "
 SELECT * FROM tbl_twitter_user 
 WHERE username = :username
 ";
 $statement = $connect->prepare($check_query);
 $check_data = array(
  ':username'  => $username
 );
 if($statement->execute($check_data))
 {
  if($statement->rowCount() > 0)
  {
   $message .= '<p><label>Username already taken</label></p>';
  }
  else
  {
   if(empty($username))
   {
    $message .= '<p><label>Username is required</label></p>';
   }
   if(empty($password))
   {
    $message .= '<p><label>Password is required</label></p>';
   }
   else
   {
    if($password != $_POST["confirm_password"])
    {
     $message .= '<p><label>Password not match</label></p>';
    }
   }
   if($message == '')
   {
    $data = array(
     ':username'  => $username,
     ':password'  => password_hash($password, PASSWORD_DEFAULT)
    );

    $query = "
    INSERT INTO tbl_twitter_user 
    (username, password) 
    VALUES (:username, :password)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $message = '<label>Registration Completed</label>';
    }
   }
  }
 }
}

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Twitter Like Follow Unfollow System in PHP using Ajax jQuery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" id="password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Re-enter Password</label>
       <input type="password" name="confirm_password" id="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-info" value="Register" />
      </div>
      <div align="center">
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


login.php


Once you have make registration system in Follow Unfollow application. After registration you have to make login page for authenticate user login details like username and password. Here password will be validate by using password_hash() method. Because at the time registration we have store password in hash format. If user has enter proper details, then his for validate user is login or not in whole system, we have store user details under $_SESSION variable.


<!--
//login.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST["login"]))
{
 $query = "
 SELECT * FROM tbl_twitter_user 
    WHERE username = :username
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
      ':username' => $_POST["username"]
     )
 );
 $count = $statement->rowCount();
 if($count > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if(password_verify($_POST['password'], $row['password']))
   {
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['username'] = $row['username'];
    header('location:index.php');
   }
   else
   {
    $message = '<label>Wrong Password</label>';
   }
  }
 }
 else
 {
  $message = '<label>Wrong Username</labe>';
 }
}


?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Twitter Like Follow Unfollow System in PHP using Ajax jQuery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Login</div>
    <div class="panel-body">
     <form method="post">
      <p class="text-danger"><?php echo $message; ?></p>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" class="btn btn-info" value="Login" />
      </div>
      <div align="center">
       <a href="register.php">Register</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


index.php


If system is validated user information, and it is correct then page will be redirect to index.php page. From this page user can share his or her post. User can view his or her post along with post of follow user by login user. On index page user can view all user list with follow and unfollow button. Most of all operation of follow and unfollow system like post new post, comment on other user post, follow and unfollow other user, repost follow yser post will be done on this page. This page will be view to only login user.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
    header('location:login.php');
}

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <?php
            include('menu.php');
            ?>
            <div class="row">
                <div class="col-md-8">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">Start Write Here</h3>
                        </div>
                        <div class="panel-body">
                            <form method="post" id="post_form">
                                <div class="form-group">
                                    <textarea name="post_content" id="post_content" maxlength="160" class="form-control" placeholder="Write your short story"></textarea>
                                </div>
                                <div class="form-group">
                                    <input type="hidden" name="action" value="insert" />
                                    <input type="submit" name="share_post" id="share_post" class="btn btn-primary" value="Share" />
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">Trending Now</h3>
                        </div>
                        <div class="panel-body">
                            <div id="post_list">

                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">User List</h3>
                        </div>
                        <div class="panel-body">
                            <div id="user_list"></div>
                        </div>
                    </div>
                </div>
            </div>
  </div>
    </body>  
</html>

<script>  
$(document).ready(function(){
 
 $('#post_form').on('submit', function(event){
        event.preventDefault();
        if($('#post_content').val() == '')
        {
            alert('Enter Story Content');
        }
        else
        {
            var form_data = $(this).serialize();
            $.ajax({
                url:"action.php",
                method:"POST",
                data:form_data,
                success:function(data)
                {
                    alert('Post has been shared');
                    $('#post_form')[0].reset();
                    fetch_post();
                }
            })
        }
    });

    fetch_post();

    function fetch_post()
    {
       var action = 'fetch_post';
       $.ajax({
            url:'action.php',
            method:"POST",
            data:{action:action},
            success:function(data)
            {
                $('#post_list').html(data);
            }
       })
    }

    fetch_user();

    function fetch_user()
    {
        var action = 'fetch_user';
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{action:action},
            success:function(data)
            {
                $('#user_list').html(data);
            }
        });
    }

    $(document).on('click', '.action_button', function(){
        var sender_id = $(this).data('sender_id');
        var action = $(this).data('action');
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{sender_id:sender_id, action:action},
            success:function(data)
            {
                fetch_user();
                fetch_post();
            }
        })
    });

    var post_id;
    var user_id;

    $(document).on('click', '.post_comment', function(){
        post_id = $(this).attr('id');
        user_id = $(this).data('user_id');
        var action = 'fetch_comment';
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{post_id:post_id, user_id:user_id, action:action},
            success:function(data){
                $('#old_comment'+post_id).html(data);
                $('#comment_form'+post_id).slideToggle('slow');
            }
        })
        
    });

    $(document).on('click', '.submit_comment', function(){
        var comment = $('#comment'+post_id).val();
        var action = 'submit_comment';
        var receiver_id = user_id;
        if(comment != '')
        {
            $.ajax({
                url:"action.php",
                method:"POST",
                data:{post_id:post_id,receiver_id:receiver_id,comment:comment,action:action},
                success:function(data)
                {
                    $('#comment_form'+post_id).slideUp('slow');
                    fetch_post();
                }
            })
        }
    });

    $(document).on('click', '.repost', function(){
        var post_id = $(this).data('post_id');
        var action = 'repost';
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{post_id:post_id, action:action},
            success:function(data)
            {
                alert(data);
                fetch_post();
            }
        })
    });
 
});  
</script>


menu.php


This file is used for make dynamic menu, here user name will be display by using $_SESSION varibale. Here in this we have add two menu for go to profile page and logout page.


                        <br />
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="index.php">Webslesson</a>
     </div>
     <ul class="nav navbar-nav navbar-right">
      <li class="dropdown">
       <a class="dropdown-toggle" data-toggle="dropdown" href="#"><?php echo $_SESSION['username']; ?>
       <span class="caret"></span></a>
       <ul class="dropdown-menu">
        <li><a href="profile.php">Profile</a></li>
        <li><a href="logout.php">Logout</a></li>
       </ul>
      </li>
     </ul>
    </div>
   </nav>


logout.php


If user want to logout from dynamic follow unfollow application, so when user click on logout link then page will redirect to this page, and on this page all $_SESSION variable will be destroy using session_destroy() function.


<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');

?>


profile.php


This file is used for edit user profile details in follow unfollow application by using PHP. Here user not only edit their profile details like username, password, name and short bio but also user can change profile image by upload image file under images folder. This image and user name will be display to other user.


<!--
//profile.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header('location:login.php');
}

$message = '';

if(isset($_POST['edit_profile']))
{
 $file_name = '';
 if(isset($_POST['profile_image']))
 {
  $file_name = $_POST['profile_image'];
 }

 if($_FILES['profile_image']['name'] != '')
 {
  if($file_name != '')
  {
   unlink('images/'.$file_name);
  }
  $image_name = explode(".", $_FILES['profile_image']['name']);
  $extension = end($image_name);
  $temporary_location = $_FILES['profile_image']['tmp_name'];
  $file_name = rand() . '.' . strtolower($extension);
  $location = 'images/' . $file_name;
  move_uploaded_file($temporary_location, $location);
 }
 $check_query = "
 SELECT * FROM tbl_twitter_user WHERE username = :username AND user_id != :user_id
 ";
 $statement = $connect->prepare($check_query);
 $statement->execute(
  array(
   ':username'  =>  trim($_POST["username"]),
   ':user_id'  =>  $_SESSION["user_id"]
  )
 );
 $total_row = $statement->rowCount();
 if($total_row > 0)
 {
  $message = '<div class="alert alert-danger">Username Already Exists</div>';
 }
 else
 {
  $data = array(
   ':username'   => trim($_POST["username"]),
   ':name'    => trim($_POST["name"]),
   ':profile_image' => $file_name,
   ':bio'    => trim($_POST["bio"]),
   ':user_id'   => $_SESSION["user_id"]
  );
  if($_POST['password'] != '')
  {
   $data[] = array(
    ':password'  => password_hash($_POST["password"], PASSWORD_DEFAULT)
   );
   $query = '
   UPDATE tbl_twitter_user SET username = :username, password = :password, name = :name, profile_image = :profile_image, bio = :bio WHERE user_id = :user_id
   ';
  }
  else
  {
   $query = '
   UPDATE tbl_twitter_user SET username = :username, name = :name, profile_image = :profile_image, bio = :bio WHERE user_id = :user_id
   ';
  }
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   $message = '<div class="alert alert-success">Profile Updated</div>';
  }
 }
}



$query = "SELECT * FROM tbl_twitter_user WHERE user_id = '".$_SESSION["user_id"]."'";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <?php 
   include('menu.php');
   ?>
   <div class="row">
    <div class="col-md-3">
    
    </div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Edit Profile</h3>
      </div>
      <div class="panel-body">
       <?php
       foreach($result as $row)
       {
        echo $message;
       ?>
       <form method="post" enctype="multipart/form-data">
        <div class="form-group">
         <label>Username</label>
         <input type="text" name="username" id="username" pattern="^[a-zA-Z0-9_.-]*$" required class="form-control" value="<?php echo $row["username"];?>" />
        </div>
        <div class="form-group">
         <label>Password</label>
         <input type="password" name="password" id="password" class="form-control" />
        </div>
        <div class="form-group">
         <label>Name</label>
         <input type="text" name="name" id="name" class="form-control" required value="<?php echo $row["name"]; ?>" />
        </div>
        <div class="form-group">
         <label>Profile Image</label>
         <input type="file" name="profile_image" id="profile_image" accept="image/*" />
         <?php
         if($row["profile_image"] != '')
         {
          echo '<img src="images/'.$row["profile_image"].'" class="img-thumbnail" width="150" />';
          echo '<input type="hidden" name="profile_image" value="'.$row["profile_image"].'" />';
         }
         ?>
        </div>
        <div class="form-group">
         <label>Short Bio</label>
         <textarea name="bio" id="bio" class="form-control"><?php echo $row["bio"]; ?></textarea>
        </div>
        <div class="form-group">
         <input type="submit" name="edit_profile" id="edit_profile" class="btn btn-primary" value="Save" />
        </div>
       </form>
       <?php
       }
       ?>
      </div>
     </div>
    </div>
    <div class="col-md-3">
    
    </div>
   </div>
  </div>
    </body>  
</html>


action.php


This file is used for perform all core operation of Insert Post, Fetch post data, fetch user data and make follow unfollow button in PHP Follow Unfollow system. This file will received request for all above operation.


<?php

//action.php

include('database_connection.php');

session_start();

if(isset($_POST['action']))
{
 $output = '';
 if($_POST['action'] == 'insert')
 {
  $data = array(
   ':user_id'   => $_SESSION["user_id"],
   ':post_content'  => $_POST["post_content"],
   ':post_datetime' => date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')))
  );
  $query = "
  INSERT INTO tbl_samples_post 
  (user_id, post_content, post_datetime) 
  VALUES (:user_id, :post_content, :post_datetime)
  ";

  $statement = $connect->prepare($query);
  $statement->execute($data);
 }

 if($_POST['action'] == 'fetch_post')
 {
  $query = "
  SELECT * FROM tbl_samples_post 
  INNER JOIN tbl_twitter_user ON tbl_twitter_user.user_id = tbl_samples_post.user_id 
  LEFT JOIN tbl_follow ON tbl_follow.sender_id = tbl_samples_post.user_id 
  WHERE tbl_follow.receiver_id = '".$_SESSION["user_id"]."' OR tbl_samples_post.user_id = '".$_SESSION["user_id"]."' 
  GROUP BY tbl_samples_post.post_id 
  ORDER BY tbl_samples_post.post_id DESC
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $total_row = $statement->rowCount();
  if($total_row > 0)
  {
   foreach($result as $row)
   {
    $profile_image = '';
    if($row['profile_image'] != '')
    {
     $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive" />';
    }
    else
    {
     $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive" />';
    }

    $repost = 'disabled';
    if($row['user_id'] != $_SESSION['user_id'])
    {
     $repost = '';
    }
    $output .= '
    <div class="jumbotron" style="padding:24px 30px 24px 30px">
     <div class="row">
      <div class="col-md-2">
       '.$profile_image.'
      </div>
      <div class="col-md-8">
       <h3><b>@'.$row["username"].'</b></h3>
       <p>'.$row["post_content"].'
       <button type="button" class="btn btn-link post_comment" id="'.$row["post_id"].'" data-user_id="'.$row["user_id"].'">'.count_comment($connect, $row["post_id"]).' Comment</button>
       <button type="button" class="btn btn-danger repost" data-post_id="'.$row["post_id"].'" '.$repost.'><span class="glyphicon glyphicon-retweet"></span>&nbsp;&nbsp;'.count_retweet($connect, $row["post_id"]).'</button>
       </p>
       <div id="comment_form'.$row["post_id"].'" style="display:none;">
        <span id="old_comment'.$row["post_id"].'"></span>
        <div class="form-group">
         <textarea name="comment" class="form-control" id="comment'.$row["post_id"].'"></textarea>
        </div>
        <div class="form-group" align="right">
         <button type="button" name="submit_comment" class="btn btn-primary btn-xs submit_comment">Comment</button>
        </div>
       </div>
      </div>
     </div>
    </div>
    ';
   }
  }
  else
  {
   $output = '<h4>No Post Found</h4>';
  }
  echo $output;
 }
 if($_POST['action'] == 'fetch_user')
 {
  $query = "
  SELECT * FROM tbl_twitter_user 
  WHERE user_id != '".$_SESSION["user_id"]."' 
  ORDER BY user_id DESC 
  LIMIT 15
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $profile_image = '';
   if($row['profile_image'] != '')
   {
    $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive" />';
   }
   else
   {
    $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive" />';
   }
   $output .= '
   <div class="row">
    <div class="col-md-4">
     '.$profile_image.'
    </div>
    <div class="col-md-8">
     <h4><b>@'.$row["username"].'</b></h4>
     '.make_follow_button($connect, $row["user_id"], $_SESSION["user_id"]).'
     <span class="label label-success"> '.$row["follower_number"].' Followers</span>
    </div>
   </div>
   <hr />
   ';
  }
  echo $output;
 }

 if($_POST['action'] == 'follow')
 {
  $query = "
  INSERT INTO tbl_follow 
  (sender_id, receiver_id) 
  VALUES ('".$_POST["sender_id"]."', '".$_SESSION["user_id"]."')
  ";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $sub_query = "
   UPDATE tbl_twitter_user SET follower_number = follower_number + 1 WHERE user_id = '".$_POST["sender_id"]."'
   ";
   $statement = $connect->prepare($sub_query);
   $statement->execute();
  }

 }

 if($_POST['action'] == 'unfollow')
 {
  $query = "
  DELETE FROM tbl_follow 
  WHERE sender_id = '".$_POST["sender_id"]."' 
  AND receiver_id = '".$_SESSION["user_id"]."'
  ";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $sub_query = "
   UPDATE tbl_twitter_user 
   SET follower_number = follower_number - 1 
   WHERE user_id = '".$_POST["sender_id"]."'
   ";
   $statement = $connect->prepare($sub_query);
   $statement->execute();
  }
 }

 if($_POST["action"] == 'submit_comment')
 {
  $data = array(
   ':post_id'  => $_POST["post_id"],
   ':user_id'  => $_SESSION["user_id"],
   ':comment'  => $_POST["comment"],
   ':timestamp' => date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')))
  );
  $query = "
  INSERT INTO tbl_comment 
  (post_id, user_id, comment, timestamp) 
  VALUES (:post_id, :user_id, :comment, :timestamp)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);

 }
 if($_POST["action"] == "fetch_comment")
 {
  $query = "
  SELECT * FROM tbl_comment 
  INNER JOIN tbl_twitter_user 
  ON tbl_twitter_user.user_id = tbl_comment.user_id 
  WHERE post_id = '".$_POST["post_id"]."' 
  ORDER BY comment_id ASC
  ";
  $statement = $connect->prepare($query);
  $output = '';
  if($statement->execute())
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $profile_image = '';
    if($row['profile_image'] != '')
    {
     $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive img-circle" />';
    }
    else
    {
     $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive img-circle" />';
    }
    $output .= '
    <div class="row">
     <div class="col-md-2">
     '.$profile_image.' 
     </div>
     <div class="col-md-10" style="margin-top:16px; padding-left:0">
      <small><b>@'.$row["username"].'</b><br />
      '.$row["comment"].'
      </small>
     </div>
    </div>
    <br />
    ';
   }
  }
  echo $output;
 }

 if($_POST['action'] == 'repost')
 {
  $query = "
  SELECT * FROM tbl_repost 
  WHERE post_id = '".$_POST["post_id"]."' 
  AND user_id = '".$_SESSION["user_id"]."'
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $total_row = $statement->rowCount();
  if($total_row > 0)
  {
   echo 'You have already repost this post';
  }
  else
  {
   $query1 = "
   INSERT INTO tbl_repost 
   (post_id, user_id) 
   VALUES ('".$_POST["post_id"]."', '".$_SESSION["user_id"]."')
   ";
   $statement = $connect->prepare($query1);
   if($statement->execute())
   {
    $query2 = "
    SELECT * FROM tbl_samples_post 
    WHERE post_id = '".$_POST["post_id"]."'
    ";
    $statement = $connect->prepare($query2);
    if($statement->execute())
    {
     $result = $statement->fetchAll();
     $post_content = '';
     foreach($result as $row)
     {
      $post_content = $row['post_content'];
     }
     $query3 = "
     INSERT INTO tbl_samples_post 
     (user_id, post_content, post_datetime) 
     VALUES ('".$_SESSION["user_id"]."', '".$post_content."', '".date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')))."')
     ";
     $statement = $connect->prepare($query3);
     if($statement->execute())
     {
      echo 'Repost done successfully';
     }
    }
   }
  }
 }
}

function count_retweet($connect, $post_id)
{
 $query = "
 SELECT * FROM tbl_repost 
 WHERE post_id = '".$post_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

function count_comment($connect, $post_id)
{
 $query = "
 SELECT * FROM tbl_comment 
 WHERE post_id = '".$post_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

function make_follow_button($connect, $sender_id, $receiver_id)
{
 $query = "
 SELECT * FROM tbl_follow 
 WHERE sender_id = '".$sender_id."' 
 AND receiver_id = '".$receiver_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  $output = '<button type="button" name="follow_button" class="btn btn-warning action_button" data-action="unfollow" data-sender_id="'.$sender_id.'"> Following</button>';
 }
 else
 {
  $output = '<button type="button" name="follow_button" class="btn btn-info action_button" data-action="follow" data-sender_id="'.$sender_id.'"><i class="glyphicon glyphicon-plus"></i> Follow</button>';
 }
 return $output;
}




?>


Remaining source code will be added very shortly.