Tuesday, 31 October 2017

Import CSV Data into Mysql in Codeigniter



We know how to import CSV Data into Mysql table using PHP script but now in this post we have discuss this topic into Codeigniter Framework. So Here we have learn how to Import Data from CSV file to Mysql Database table in Codeigniter Framework. Importing of data in Codeigniter framework required different coding style then simple PHP script because it is an MVC (Model View Controller) framework. For do this task we have create three different file into Controllers, models and views folder. First request will be received at controller folder then it will send request to models files and it will do required database operation and return data to controller method and after this it will print data in view files. This way MVC framework will execute code.



Importing of Bulk Data through CSV file is one of the required feature of any web application and it will reduce time to insert data one by one. Here we want to import data from CSV file to Mysql database in Codeigniter framework. There is no any library for CSV file in Codeigniter, but we have search on internet and we have find one library 'csvimport' which is developed for import of CSV data in Codeigniter framework. So we have use 'csvimport' library for importing of data from CSV file to Mysql database in Codeigniter Framework. This library will required only CSV file location and by using this get_array() method of 'csvimport' library we can easily convert CSV data to php array in controller file code. After getting CSV file data into PHP array we can easily play with that data.

If you have import bulk data from CSV file and if you have use Codeigniter framework for web application development then you can use Codeigniter Database library insert_batch() method. By using this method we can execute multiple Insert data query in single query execution. So, by using this method we can import large amount of data in a very short time because by using 'csvimport' library we have got array of CSV file data and after this we have use insert_batch() we have directly import all data in single query execution. So this is one benefit of Codeigniter framework if you have import large data. Here we have also use Ajax Jquery so all operation has been done without refresh of webpage. Here we have upload CSV file by using Ajax Jquery FormData object. So this way we can Import Data from CSV file in Codeigniter Framework by using Ajax JQuery.







Source Code


controllers - Csv_import.php



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

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

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

 function load_data()
 {
  $result = $this->csv_import_model->select();
  $output = '
   <h3 align="center">Imported User Details from CSV File</h3>
        <div class="table-responsive">
         <table class="table table-bordered table-striped">
          <tr>
           <th>Sr. No</th>
           <th>First Name</th>
           <th>Last Name</th>
           <th>Phone</th>
           <th>Email Address</th>
          </tr>
  ';
  $count = 0;
  if($result->num_rows() > 0)
  {
   foreach($result->result() as $row)
   {
    $count = $count + 1;
    $output .= '
    <tr>
     <td>'.$count.'</td>
     <td>'.$row->first_name.'</td>
     <td>'.$row->last_name.'</td>
     <td>'.$row->phone.'</td>
     <td>'.$row->email.'</td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
   <tr>
       <td colspan="5" align="center">Data not Available</td>
      </tr>
   ';
  }
  $output .= '</table></div>';
  echo $output;
 }

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


models - Csv_import_model.php



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

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


views - csv_import.php



<html>
<head>
    <title>How to Import CSV Data into Mysql using 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 Import CSV Data into Mysql using Codeigniter</h3>
  <br />

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

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

 load_data();

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

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



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_user`
--

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Saturday, 28 October 2017

How to send email with attachment in PHP



In this Post we have discuss one more topic related to PHPMailer Class and here we have discuss how can we send an Email with File attachment in PHP by using PHPMailer Library. We have received so many request from our viewer for publish web tutorial on sending of Email with Attachment by using PHPMailer from PHP form submission. We have already publish web tutorial on how to send email on PHP form submission and how can we send bulk email by using PHP with Ajax without refresh of web page. But in this post we have discuss something advance like how to send email with attach uploaded file by using PHPMailer Library in PHP.

PHPMailer is a PHP Class library which are used for sending email and this class has more functionality compared to the simple PHP mail() function including file attachment also. It is very useful if you have SMTP details then you can use that details into your PHP script and from your application you can send an email and you can also attach file with email on form submission by using this PHPMailer class.

For discuss how can we attach file sending of email by using PHPMailer in PHP. So here we have make simple programmer registration form in which programmer can fill their details. In that registration form we have add one file tag for programmer to attach resume. In this form all fields are compulsory and for form validation we have use HTML 5 validation. By using this validation we do not want to required to write any additional code for form validation. For attach file in an Email, so want to first upload file on our server folder and from that uploaded file path we can attach within mail by using AddAttachment() method of PHPMailer class. After attachment of file we can send email with file attachment using PHPMailer library. After successfully sending of email we have remove uploaded file from our space. So this way for attach file with email sending we want to temporary store on our space and after remove from our space. This is our simple tutorial on How to send email with attachment in PHP by using PHPMailer.




Source Code


index.php



<?php
//index.php

$message = '';

function clean_text($string)
{
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;
}

if(isset($_POST["submit"]))
{
 $programming_languages = '';
 foreach($_POST["programming_languages"] as $row)
 {
  $programming_languages .= $row . ', ';
 }
 $programming_languages = substr($programming_languages, 0, -2);
 $path = 'upload/' . $_FILES["resume"]["name"];
 move_uploaded_file($_FILES["resume"]["tmp_name"], $path);
 $message = '
  <h3 align="center">Programmer Details</h3>
  <table border="1" width="100%" cellpadding="5" cellspacing="5">
   <tr>
    <td width="30%">Name</td>
    <td width="70%">'.$_POST["name"].'</td>
   </tr>
   <tr>
    <td width="30%">Address</td>
    <td width="70%">'.$_POST["address"].'</td>
   </tr>
   <tr>
    <td width="30%">Email Address</td>
    <td width="70%">'.$_POST["email"].'</td>
   </tr>
   <tr>
    <td width="30%">Progamming Language Knowledge</td>
    <td width="70%">'.$programming_languages.'</td>
   </tr>
   <tr>
    <td width="30%">Experience Year</td>
    <td width="70%">'.$_POST["experience"].'</td>
   </tr>
   <tr>
    <td width="30%">Phone Number</td>
    <td width="70%">'.$_POST["mobile"].'</td>
   </tr>
   <tr>
    <td width="30%">Additional Information</td>
    <td width="70%">'.$_POST["additional_information"].'</td>
   </tr>
  </table>
 ';
 
 require 'class/class.phpmailer.php';
 $mail = new PHPMailer;
 $mail->IsSMTP();        //Sets Mailer to send message using SMTP
 $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
 $mail->Port = '80';        //Sets the default SMTP server port
 $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
 $mail->Username = 'xxxxxxx';     //Sets SMTP username
 $mail->Password = 'xxxxxxx';     //Sets SMTP password
 $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
 $mail->From = $_POST["email"];     //Sets the From email address for the message
 $mail->FromName = $_POST["name"];    //Sets the From name of the message
 $mail->AddAddress('web-tutorial@programmer.net', 'Webslesson');  //Adds a "To" address
 $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
 $mail->IsHTML(true);       //Sets message type to HTML
 $mail->AddAttachment($path);     //Adds an attachment from a path on the filesystem
 $mail->Subject = 'Application for Programmer Registration';    //Sets the Subject of the message
 $mail->Body = $message;       //An HTML or plain text message body
 if($mail->Send())        //Send an Email. Return true on success or false on error
 {
  $message = '<div class="alert alert-success">Application Successfully Submitted</div>';
  unlink($path);
 }
 else
 {
  $message = '<div class="alert alert-danger">There is an Error</div>';
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Send Email with Attachment in PHP using PHPMailer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <div class="row">
    <div class="col-md-8" style="margin:0 auto; float:none;">
     <h3 align="center">Send Email with Attachment in PHP using PHPMailer</h3>
     <br />
     <h4 align="center">Programmer Register Here</h4><br />
     <?php print_r($message); ?>
     <form method="post" enctype="multipart/form-data">
      <div class="row">
       <div class="col-md-6">
        <div class="form-group">
         <label>Enter Name</label>
         <input type="text" name="name" placeholder="Enter Name" class="form-control" required />
        </div>
        <div class="form-group">
         <label>Enter Address</label>
         <textarea name="address" placeholder="Enter Address" class="form-control" required></textarea>
        </div>
        <div class="form-group">
         <label>Enter Email Address</label>
         <input type="email" name="email" class="form-control" placeholder="Enter Email Address" required />
        </div>
        <div class="form-group">
         <label>Select Programming Language</label>
         <select name="programming_languages[]" class="form-control" multiple required style="height:150px;">
          <option value=".NET">.NET</option><option value="Android">Android</option><option value="ASP">ASP</option><option value="Blackberry">Blackberry</option><option value="C">C</option><option value="C++">C++</option><option value="COCOA">COCOA</option><option value="CSS">CSS</option><option value="DHTML">DHTML</option><option value="Drupal">Drupal</option><option value="Flash">Flash</option><option value="HTML">HTML</option><option value="HTML 5">HTML 5</option><option value="IPAD">IPAD</option><option value="IPHONE">IPHONE</option><option value="Java">Java</option><option value="Java Script">Java Script</option><option value="Joomla">Joomla</option><option value="LAMP">LAMP</option><option value="Linux">Linux</option><option value="MAC OS">MAC OS</option><option value="Magento">Magento</option><option value="MySQL">MySQL</option><option value="Oracle">Oracle</option><option value="PayPal">PayPal</option><option value="Perl">Perl</option><option value="PHP">PHP</option><option value="Ruby on Rails">Ruby on Rails</option><option value="Salesforce.com">Salesforce.com</option><option value="SEO">SEO</option>
         </select>
        </div>
        
       </div>
       <div class="col-md-6">
        <div class="form-group">
         <label>Select Year of Experience</label>
         <select name="experience" class="form-control" required>
          <option value="">Select Experience</option>
          <option value="0-1 years">0-1 years</option>
          <option value="2-3 years">2-3 years</option>
          <option value="4-5 years">4-5 years</option>
          <option value="6-7 years">6-7 years</option>
          <option value="8-9 years">8-9 years</option>
          <option value="10 or more years">10 or more years</option>
         </select>
        </div>
        <div class="form-group">
         <label>Enter Mobile Number</label>
         <input type="text" name="mobile" placeholder="Enter Mobile Number" class="form-control" pattern="\d*" required />
        </div>
        <div class="form-group">
         <label>Select Your Resume</label>
         <input type="file" name="resume" accept=".doc,.docx, .pdf" required />
        </div>
        <div class="form-group">
         <label>Enter Additional Information</label>
         <textarea name="additional_information" placeholder="Enter Additional Information" class="form-control" required rows="8"></textarea>
        </div>
       </div>
      </div>
      <div class="form-group" align="center">
       <input type="submit" name="submit" value="Submit" class="btn btn-info" />
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>





Wednesday, 25 October 2017

Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP



Sometimes we want to required add or remove dynamic html fields in a form. We have already seen how to add or remove simple html input fields dynamically in a form, but how to add or remove dynamic select box into form dynamically. So We have make this simple tutorial to learn how can we add or remove select box data dynamically using Jquery and how can we insert multiple select box data into Mysql table by using Ajax with PHP without refresh of webpage.

For Add or remove drop down list box data dynamically into form, we have developed a jquery script by using script we can add or remove multiple select box fields very easily. In this script also useful for insert multiple values of drop down list box in PHP by using Ajax. In this post we have discuss how to generate dynamic select box HTML fields in a form while filling of form and after adding multiple select box data into the database. For this we have used Jquery to developed this type of functionality with very short, simple and powerful. By using this script we can add or remove dynamic select box fields very easily. After adding multiple select box fields and submit those select box value into PHP script by using Ajax and inserted into Mysql table.

In this post to learn how to add or remove dynamic Select Box data dynamically using Jquery and insert into Mysql table using Ajax with PHP. So Here we have make simple invoice script for add multiple item data into single order. In this example Item name and Quantity data has been insert into text box field but for enter Item Unit data we have use dynamic select box. So here we have use dynamic drop down list box for enter Item unit data and here when we have add one more item then this dynamic select box with filled data has been generated for select Item unit value. Here Add or remove of input fields with dynamic drop down list box code has been generated by using Jquery script. After adding and removing all item details we will insert multiple item data with dynamic select box data into Mysql table by using Ajax with PHP, so here data multiple data will be inserted without refresh of web page.




Source Code


index.php



<?php
//index.php

$connect = new PDO("mysql:host=localhost;dbname=testing4", "root", "");
function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
   <br />
   <h4 align="center">Enter Item Details</h4>
   <br />
   <form method="post" id="insert_form">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
      <tr>
       <th>Enter Item Name</th>
       <th>Enter Quantity</th>
       <th>Select Unit</th>
       <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
      </tr>
     </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Insert" />
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
  html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
  html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
  $('#item_table').append(html);
 });
 
 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.item_name').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_quantity').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_unit').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Unit at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>


insert.php



<?php
//insert.php;

if(isset($_POST["item_name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing4", "root", "");
 $order_id = uniqid();
 for($count = 0; $count < count($_POST["item_name"]); $count++)
 {  
  $query = "INSERT INTO tbl_order_items 
  (order_id, item_name, item_quantity, item_unit) 
  VALUES (:order_id, :item_name, :item_quantity, :item_unit)
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':order_id'   => $order_id,
    ':item_name'  => $_POST["item_name"][$count], 
    ':item_quantity' => $_POST["item_quantity"][$count], 
    ':item_unit'  => $_POST["item_unit"][$count]
   )
  );
 }
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'ok';
 }
}
?>


Database



--
-- Database: `testing4`
--

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

--
-- Table structure for table `tbl_order_items`
--

CREATE TABLE IF NOT EXISTS `tbl_order_items` (
  `order_items_id` int(11) NOT NULL,
  `order_id` varchar(150) NOT NULL,
  `item_name` varchar(250) NOT NULL,
  `item_quantity` int(11) NOT NULL,
  `item_unit` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `tbl_unit`
--

CREATE TABLE IF NOT EXISTS `tbl_unit` (
  `unit_id` int(11) NOT NULL,
  `unit_name` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_unit`
--

INSERT INTO `tbl_unit` (`unit_id`, `unit_name`) VALUES
(1, 'Bags'),
(2, 'Bottles'),
(3, 'Box'),
(4, 'Dozens'),
(5, 'Feet'),
(6, 'Gallon'),
(7, 'Grams'),
(8, 'Inch'),
(9, 'Kg'),
(10, 'Liters'),
(11, 'Meter'),
(12, 'Nos'),
(13, 'Packet'),
(14, 'Rolls');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_order_items`
--
ALTER TABLE `tbl_order_items`
  ADD PRIMARY KEY (`order_items_id`);

--
-- Indexes for table `tbl_unit`
--
ALTER TABLE `tbl_unit`
  ADD PRIMARY KEY (`unit_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_order_items`
--
ALTER TABLE `tbl_order_items`
  MODIFY `order_items_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `tbl_unit`
--
ALTER TABLE `tbl_unit`
  MODIFY `unit_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15;

Tuesday, 17 October 2017

How to Send Bulk Email in PHP using PHPMailer with Ajax JQuery



Most of the Website has the sending of email feature like send single email or bulk email. So In this post we have discuss topic like how can we send bulk email by using PHP script with PHPMailer Ajax and Jquery. We have use PHPMailer Library because PHP mail() function will not work on localhost. So we have discuss how can we send single or bulk email from localhost in PHP with PHPMailer by using Ajax Jquery. So we can send single or bulk email without refresh or webpage.

We have use SMTP for send bulk mail because SMTP us the most suggested way to send email from localhost or online server. If we have use SMTP to send mail so PHP has nice library PHPMailer library which allow to send email via SMTP by providing required credential. If you have any web hosting email account then your hosting company will provide SMTP credential like username, password, outgoing and incoming server address and port number. By using this information you can configured this details into PHPMailer class and then after you can send email from your script.

In this post we have make simple application from which we can send bulk email to customer by single click. Here we have use Jquery with Ajax so we can send email without refresh of web page. When we have click on button then it will collect email from checkboxes data attribute by using Jquery and after collecting data it will send this data to Ajax request and via Ajax request it will transfer to PHP script and in this we have use PHPMailer class with required SMTP configuration and it will send bulk email and after sending all email successfully it will send data to Ajax request and it will display on web page. This way we can use Ajax with Jquery for Send bulk email by using PHP with PHPMailer Library.









Source Code


index.php



<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM customer ORDER BY customer_id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Send Bulk Email using PHPMailer with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Send Bulk Email using PHPMailer with PHP Ajax</h3>
   <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <tr>
      <th>Customer Name</th>
      <th>Email</th>
      <th>Select</th>
      <th>Action</th>
     </tr>
     <?php
     $count = 0;
     foreach($result as $row)
     {
      $count++;
      echo '
      <tr>
       <td>'.$row["customer_name"].'</td>
       <td>'.$row["customer_email"].'</td>
       <td>
        <input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
       </td>
       <td><button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button></td>
      </tr>
      ';
     }
     ?>
     <tr>
      <td colspan="3"></td>
      <td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
     </td>
    </table>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('.email_button').click(function(){
  $(this).attr('disabled', 'disabled');
  var id = $(this).attr("id");
  var action = $(this).data("action");
  var email_data = [];
  if(action == 'single')
  {
   email_data.push({
    email: $(this).data("email"),
    name: $(this).data("name")
   });
  }
  else
  {
   $('.single_select').each(function(){
    if($(this). prop("checked") == true)
    {
     email_data.push({
      email: $(this).data("email"),
      name: $(this).data('name')
     });
    }
   });
  }
  
  $.ajax({
   url:"send_mail.php",
   method:"POST",
   data:{email_data:email_data},
   beforeSend:function(){
    $('#'+id).html('Sending...');
    $('#'+id).addClass('btn-danger');
   },
   success:function(data){
    if(data = 'ok')
    {
     $('#'+id).text('Success');
     $('#'+id).removeClass('btn-danger');
     $('#'+id).removeClass('btn-info');
     $('#'+id).addClass('btn-success');
    }
    else
    {
     $('#'+id).text(data);
    }
    $('#'+id).attr('disabled', false);
   }
   
  });
 });
});
</script>


send_mail.php



<?php
//send_mail.php

if(isset($_POST['email_data']))
{
 require 'class/class.phpmailer.php';
 $output = '';
 foreach($_POST['email_data'] as $row)
 {
  $mail = new PHPMailer;
  $mail->IsSMTP();        //Sets Mailer to send message using SMTP
  $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
  $mail->Port = '80';        //Sets the default SMTP server port
  $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
  $mail->Username = 'xxxxxxxxxx';     //Sets SMTP username
  $mail->Password = 'xxxxxxxxxx';     //Sets SMTP password
  $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
  $mail->From = 'info@webslesson.com';   //Sets the From email address for the message
  $mail->FromName = 'Webslesson';     //Sets the From name of the message
  $mail->AddAddress($row["email"], $row["name"]); //Adds a "To" address
  $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
  $mail->IsHTML(true);       //Sets message type to HTML
  $mail->Subject = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'; //Sets the Subject of the message
  //An HTML or plain text message body
  $mail->Body = '
  <p>Sed at odio sapien. Vivamus efficitur, nibh sit amet consequat suscipit, ante quam eleifend felis, mattis dignissim lectus ipsum eget lectus. Nullam aliquam tellus vitae nisi lobortis, in hendrerit metus facilisis. Donec iaculis viverra purus a efficitur. Maecenas dignissim finibus ultricies. Curabitur ultricies tempor mi ut malesuada. Morbi placerat neque blandit, volutpat felis et, tincidunt nisl.</p>
  <p>In imperdiet congue sollicitudin. Quisque finibus, ipsum eget sagittis pellentesque, eros leo tempor ante, interdum mollis tortor diam ut nisl. Vivamus odio mi, congue eu ipsum vulputate, consequat hendrerit sapien. Aenean mauris nibh, ultrices accumsan ultricies eget, ultrices ut dui. Donec bibendum lectus a nibh interdum, vel condimentum eros auctor.</p>
  <p>Quisque dignissim pharetra tortor, sit amet auctor enim euismod at. Sed vitae enim at augue convallis pellentesque. Donec rhoncus nisi et posuere fringilla. Phasellus elementum iaculis convallis. Curabitur laoreet, dui eget lacinia suscipit, quam erat vehicula nulla, non ultrices elit massa eu dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vulputate mauris vel ultricies tempor.</p>
  <p>Mauris est leo, tincidunt sit amet lacinia eget, consequat convallis justo. Morbi sollicitudin purus arcu. Suspendisse pellentesque interdum enim non consectetur. Etiam eleifend pharetra ante a feugiat.</p>
  ';

  $mail->AltBody = '';

  $result = $mail->Send();      //Send an Email. Return true on success or false on error

  if($result["code"] == '400')
  {
   $output .= html_entity_decode($result['full_error']);
  }

 }
 if($output == '')
 {
  echo 'ok';
 }
 else
 {
  echo $output;
 }
}

?>

Friday, 13 October 2017

Send an Email on Form Submission using PHP with PHPMailer



Sending of an Email is most required feature of any Website for connect user to system, so in this post we have discuss how can we send email on form submission by using PHP script with PHPMailer Library class. PHPMailer class is an other alternative of PHP mail() function to send an Email by using SMTP settings. If you have an Email hosting account then you can use this PHPMailer class for send an email from your website by provide SMTP credential.

In this post we have learn how can we send email from localhost in PHP script by using PHPMailer. If you have use PHP mail() function for send an email then you have to set Email configuration in your php.ini file but if you have use PHPMailer class then you can use any Email hosting account for send an email on form submission or any event in your website as you set.

Here we will learn how to use PHPMailer in PHP and how can we configure into our PHP script or form submission event. For use this class we have required SMTP username and password and we also know SMTP host server name also. If you do not know, so please collect this information first for use this class, without knowing this information we can not configured PHPMailer class into our web application. If we have successfully configured SMTP settings then we can send Email via SMTP server in PHP using PHPMailer. In this post we have make simple contact form for user to send his or her feedback to owner of website via Email send using PHPMailer.






Source Code


index.php



<?php
//index.php

$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';

function clean_text($string)
{
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;
}

if(isset($_POST["submit"]))
{
 if(empty($_POST["name"]))
 {
  $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
 }
 else
 {
  $name = clean_text($_POST["name"]);
  if(!preg_match("/^[a-zA-Z ]*$/",$name))
  {
   $error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
  }
 }
 if(empty($_POST["email"]))
 {
  $error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
 }
 else
 {
  $email = clean_text($_POST["email"]);
  if(!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
   $error .= '<p><label class="text-danger">Invalid email format</label></p>';
  }
 }
 if(empty($_POST["subject"]))
 {
  $error .= '<p><label class="text-danger">Subject is required</label></p>';
 }
 else
 {
  $subject = clean_text($_POST["subject"]);
 }
 if(empty($_POST["message"]))
 {
  $error .= '<p><label class="text-danger">Message is required</label></p>';
 }
 else
 {
  $message = clean_text($_POST["message"]);
 }
 if($error == '')
 {
  require 'class/class.phpmailer.php';
  $mail = new PHPMailer;
  $mail->IsSMTP();        //Sets Mailer to send message using SMTP
  $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts
  $mail->Port = '80';        //Sets the default SMTP server port
  $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
  $mail->Username = 'xxxxxxxxxx';     //Sets SMTP username
  $mail->Password = 'xxxxxxxxxx';     //Sets SMTP password
  $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
  $mail->From = $_POST["email"];     //Sets the From email address for the message
  $mail->FromName = $_POST["name"];    //Sets the From name of the message
  $mail->AddAddress('info@find2rent.com', 'Name');//Adds a "To" address
  $mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
  $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
  $mail->IsHTML(true);       //Sets message type to HTML    
  $mail->Subject = $_POST["subject"];    //Sets the Subject of the message
  $mail->Body = $_POST["message"];    //An HTML or plain text message body
  if($mail->Send())        //Send an Email. Return true on success or false on error
  {
   $error = '<label class="text-success">Thank you for contacting us</label>';
  }
  else
  {
   $error = '<label class="text-danger">There is an Error</label>';
  }
  $name = '';
  $email = '';
  $subject = '';
  $message = '';
 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Send an Email on Form Submission using PHP with PHPMailer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <div class="row">
    <div class="col-md-8" style="margin:0 auto; float:none;">
     <h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
     <br />
     <?php echo $error; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Name</label>
       <input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
      </div>
      <div class="form-group">
       <label>Enter Email</label>
       <input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
      </div>
      <div class="form-group">
       <label>Enter Subject</label>
       <input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
      </div>
      <div class="form-group">
       <label>Enter Message</label>
       <textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
      </div>
      <div class="form-group" align="center">
       <input type="submit" name="submit" value="Submit" class="btn btn-info" />
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>

Wednesday, 11 October 2017

Create Stylish Toggles Checkboxes & Use in Form with PHP Ajax



This tutorial is on How to Make Stylish toggles button from Check box HTML tag by using Bootstrap Toggle Jquery plugin and after creating checkbox toggle button how can we pass value of that button into Form by using Jquery and Insert into Mysql table by using Ajax with PHP. We all know web application must be with stylish user interface, so if UI of any web application has something different then it will attract more user and user can also easily understand how can we use this application.

Bootstrap Toggle plugin will convert simple check box into highly flexible toggles button. So if user has come on site then he can understand how can use our web application. If you we have use Bootstrap for our web application UI then this plugin can be easily integrate into our application. Because this plugin is compatible with Bootstrap Library.

Suppose you have developed simple form and in this you have used checkbox tag for any purpose, but simple checkbox UI is very common and we can see in any web based application but if you want to make form something different UI for checkbox then we can use this plugin because it will convert simple checkbox into stylish toggle button with two option and user can select option and by using this plugin we can use single checkbox for select one option from two available option. This plugin will easily to user.

So, this post we have discuss how to initialize this plugin and we have also discuss some basic option like how can we define text on toggle button how can we change background color of toggle button. Then after we will seen how can we use value of toggle button as form field and lastly how can insert value of toggle button into Mysql table by using Ajax with PHP.






Source Code



<?php
//index.php
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Make Stylish Toggles Checkboxes  & Use in Form with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
  <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
  <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">Make Stylish Toggles Checkboxes & Use in Form with PHP Ajax</h2><br /><br />
   <form method="post" id="insert_data">
    <div class="form-group">
     <label>Enter Name</label>
     <input type="text" name="name" id="name" class="form-control" />
    </div>
    <div class="form-group">
     <label>Define Gender</label>
     <div class="checkbox">
      <input type="checkbox" name="gender" id="gender" checked />
     </div>
    </div>
    <input type="hidden" name="hidden_gender" id="hidden_gender" value="Male" />
    <br />
    <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#gender').bootstrapToggle({
  on: 'Male',
  off: 'Female',
  onstyle: 'success',
  offstyle: 'danger'
 });

 $('#gender').change(function(){
  if($(this).prop('checked'))
  {
   $('#hidden_gender').val('Male');
  }
  else
  {
   $('#hidden_gender').val('Female');
  }
 });

 $('#insert_data').on('submit', function(event){
  event.preventDefault();
  if($('#name').val() == '')
  {
   alert("Please Enter Name");
   return false;
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data){
     if(data == 'done')
     {
      $('#insert_data')[0].reset();
      $('#gender').bootstrapToggle('on');
      alert("Data Inserted");
     }
    }
   });
  }
 });

});
</script>


insert.php



<?php
//insert.php

if(isset($_POST["name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 $query = "
 INSERT INTO tbl_users (name, gender) 
 VALUES(:name, :gender)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':name'   => $_POST['name'],
   ':gender'  => $_POST['hidden_gender']
  )
 );

 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'done';
 }
}

?>

Sunday, 8 October 2017

Insert Dynamic Multi Select Box Data using Jquery Ajax PHP



In this tutorial we are going to learn how to insert multiple select box data into mysql table by using Ajax jquery with php. In this post we will make stylish multi select box with easy to use user interface, so for this we have use Jquery plugin light weight multi select, by using this light weight jquery plugin we can converts multi select box into two different selection box, when we have click on particular option of left select box then that value will be append into right select box and suppose we want to remove value from right select box then we have simply click on particular option that value will be removed from right box to left. This type of user interface we should use if we have multiple option select and from this interface we can easily understand which option we have select and which are left for selecting.

We will make simple dynamic dropdown list box for insert country state and multiple city data into table, from country and state drop down box we can select single data but from city multi select we can select multiple city at the same time. And lastly all select box data has been dependent on it's parent select box. That means city data depend on state selection and state data depend on country selection. In short all dropdown list are dynamic dependent. If we want to select with multiple item from single select box and this plugin is light weight and it is easy to use. If we have go to user interface wise it is easy to understand to user which option he has select from select box, but this plugin has one draw back is that it is not responsive. So here we have discuss how to insert multi select box data by using light weight multi select jquery plugin with Ajax and PHP.




Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
?>


index.php



<?php
//index.php

include('database_connection.php');

$country = '';

$query = "
 SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC
";
$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
 $country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
  <script src="jquery.lwMultiSelect.js"></script>
  <link rel="stylesheet" href="jquery.lwMultiSelect.css" />
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</h2><br /><br />
   <form method="post" id="insert_data">
    <select name="country" id="country" class="form-control action">
     <option value="">Select Country</option>
     <?php echo $country; ?>
    </select>
    <br />
    <select name="state" id="state" class="form-control action">
     <option value="">Select State</option>
    </select>
    <br />
    <select name="city" id="city" multiple class="form-control">
    </select>
    <br />
    <input type="hidden" name="hidden_city" id="hidden_city" />
    <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
   </form>
  </div>
 </body>
</html>

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

 $('#city').lwMultiSelect();

 $('.action').change(function(){
  if($(this).val() != '')
  {
   var action = $(this).attr("id");
   var query = $(this).val();
   var result = '';
   if(action == 'country')
   {
    result = 'state';
   }
   else
   {
    result = 'city';
   }
   $.ajax({
    url:'fetch.php',
    method:"POST",
    data:{action:action, query:query},
    success:function(data)
    {
     $('#'+result).html(data);
     if(result == 'city')
     {
      $('#city').data('plugin_lwMultiSelect').updateList();
     }
    }
   })
  }
 });

 $('#insert_data').on('submit', function(event){
  event.preventDefault();
  if($('#country').val() == '')
  {
   alert("Please Select Country");
   return false;
  }
  else if($('#state').val() == '')
  {
   alert("Please Select State");
   return false;
  }
  else if($('#city').val() == '')
  {
   alert("Please Select City");
   return false;
  }
  else
  {
   $('#hidden_city').val($('#city').val());
   $('#action').attr('disabled', 'disabled');
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     $('#action').attr("disabled", "disabled");
     if(data == 'done')
     {
      $('#city').html('');
      $('#city').data('plugin_lwMultiSelect').updateList();
      $('#city').data('plugin_lwMultiSelect').removeAll();
      $('#insert_data')[0].reset();
      alert('Data Inserted');
     }
    }
   });
  }
 });

});
</script>


fetch.php



<?php
//fetch.php

if(isset($_POST['action']))
{
 include('database_connection.php');

 $output = '';

 if($_POST["action"] == 'country')
 {
  $query = "
  SELECT state FROM country_state_city 
  WHERE country = :country 
  GROUP BY state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':country'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  $output .= '<option value="">Select State</option>';
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
  }
 }
 if($_POST["action"] == 'state')
 {
  $query = "
  SELECT city FROM country_state_city 
  WHERE state = :state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':state'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
  }


 }
 echo $output;
}

?>


insert.php



<?php
//insert.php

if(isset($_POST['country']))
{
 include('database_connection.php');
 $query = "
 INSERT INTO country_state_city_form_data (country, state, city) 
 VALUES(:country, :state, :city)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':country'  => $_POST['country'],
   ':state'  => $_POST['state'],
   ':city'   => $_POST['hidden_city']
  )
 );
 $result = $statement->fetchAll();

 if(isset($result))
 {
  echo 'done';
 }

}

?>





Wednesday, 4 October 2017

How to create PHP Login Script using Cookies



If you are looking for tutorial on How to create PHP Login Logout page by using Cookies, then you have come to right place, in this post we have describe How to make PHP login script by using Cookies. We have already describe How to Create PHP Login form by using Session with different option like PHP PDO, object Oriented and in Codeigniter also. But in all post we have use Session for make PHP login logout script. But here we have implement Cookies for developed PHP Login Logout script.

We all know Session are more secured than Cookies. Sessions data are store on server while Cookies data are store on user browser. Cookies are lighter than Session and Cookies can be easily hack. These are all drawback of using Cookies for Login system. But here we have only describe we can also use Cookies for developing Login system in PHP. We have make this tutorial only for learning purpose.

So, In this post we will make simple Login form with logout form. For password verification we have use password_verify() hash method for validate encrypted password. If user has enter proper data then after in this script we have create one cookie variable which we can access from whole system by using setcookies function. After creating coookie variable now we want to validate that cookie variable, so we have use isset() function, by using this function we can validate this $_COOKIE variable. After login into system now we want to logout from system, for logout from system also we have setcookie() and by using this function we can also destroy cookie value also. So, this way we can use setcookie() function we can create or destroy value also. After destroying cookie value now we can logout from system. This way we can use COOKIE for developing login form in PHP







Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing2", "root", "");
?>


login.php



<?php
//login.php

include("database_connection.php");

if(isset($_COOKIE["type"]))
{
 header("location:index.php");
}

$message = '';

if(isset($_POST["login"]))
{
 if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
 {
  $message = "<div class='alert alert-danger'>Both Fields are required</div>";
 }
 else
 {
  $query = "
  SELECT * FROM user_details 
  WHERE user_email = :user_email
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    'user_email' => $_POST["user_email"]
   )
  );
  $count = $statement->rowCount();
  if($count > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if(password_verify($_POST["user_password"], $row["user_password"]))
    {
     setcookie("type", $row["user_type"], time()+3600);
     header("location:index.php");
    }
    else
    {
     $message = '<div class="alert alert-danger">Wrong Password</div>';
    }
   }
  }
  else
  {
   $message = "<div class='alert alert-danger'>Wrong Email Address</div>";
  }
 }
}


?>

<!DOCTYPE html>
<html>
 <head>
  <title>How to create PHP Login Script using Cookies</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">How to create PHP Login Script using Cookies</h2>
   <br />
   <div class="panel panel-default">

    <div class="panel-heading">Login</div>
    <div class="panel-body">
     <span><?php echo $message; ?></span>
     <form method="post">
      <div class="form-group">
       <label>User Email</label>
       <input type="text" name="user_email" id="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" id="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="login" id="login" class="btn btn-info" value="Login" />
      </div>
     </form>
    </div>
   </div>
   <br />
   <p>Admin email - john_smith@gmail.com</p>
   <p>Admin Password - password</p>
   <p>All user password is 'password'</p>
  </div>
 </body>
</html>


logout.php



<?php
//logout.php
setcookie("type", "", time()-3600);

header("location:login.php");

?>


index.php



<?php
//index.php

if(!isset($_COOKIE["type"]))
{
 header("location:login.php");
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>How to create PHP Login Script using Cookies</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">How to create PHP Login Script using Cookies</h2>
   <br />
   <div align="right">
    <a href="logout.php">Logout</a>
   </div>
   <br />
   <?php
   if(isset($_COOKIE["type"]))
   {
    echo '<h2 align="center">Welcome User</h2>';
   }
   ?>
  </div>
 </body>
</html>


Database



--
-- Database: `testing2`
--

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

--
-- Table structure for table `user_details`
--

CREATE TABLE IF NOT EXISTS `user_details` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(200) NOT NULL,
  `user_password` varchar(200) NOT NULL,
  `user_name` varchar(200) NOT NULL,
  `user_type` enum('master','user') NOT NULL,
  `user_image` varchar(150) NOT NULL,
  `user_status` enum('Active','Inactive') NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_details`
--

INSERT INTO `user_details` (`user_id`, `user_email`, `user_password`, `user_name`, `user_type`, `user_image`, `user_status`) VALUES
(1, 'john_smith@gmail.com', '$2y$10$cHpf3TzonURXDENRiRF0de1ycSfnM4NJ27sdwyUCf5L.sewDlkCBe', 'John Smith', 'master', 'john_smith.jpg', 'Active'),
(2, 'dona_huber@gmail.com', '$2y$10$lcLYyNeK1adgzYcBplv45uuXHFuFyWYThnj3nB2SZ/LbQvtWSoGjO', 'Dona Huber', 'user', 'dona_huber.jpg', 'Active'),
(3, 'roy_hise@gmail.com', '$2y$10$XlyVI9an5B6rHW3SS9vQpesJssKJxzMQYPbSaR7dnpWjDI5fpxJSS', 'Roy Hise', 'user', 'roy_hise.jpg', 'Active'),
(4, 'peter_goad@gmail.com', '$2y$10$n1B.FdHNwufTkmzp/pNqc.EiwjB8quQ1tBCEC7nkaldI5pS.et04e', 'Peter Goad', 'user', 'peter_goad.jpg', 'Active'),
(5, 'sarah_thomas@gmail.com', '$2y$10$s57SErOPlgkIZf1lxzlX3.hMt8LSSKaYig5rusxghDm7LW8RtQc/W', 'Sarah Thomas', 'user', 'sarah_thomas.jpg', 'Active'),
(6, 'edna_william@gmail.com', '$2y$10$mfMXnH.TCmg5tlYRhqjxu.ILly8s9.qsLKOpyxgUl6h1fZt6x/B5C', 'Edna William', 'user', 'edna_william.jpg', 'Active');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_details`
--
ALTER TABLE `user_details`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_details`
--
ALTER TABLE `user_details`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

Monday, 2 October 2017

How to Search Table Data by Bootstrap Typeahead with PHP Ajax



Searching of table data is very required feature in any web application, so here we have discuss something like that. In this post we have learn how to search or filter table data by autocomplete textbox using bootstrap typeahead plugin with PHP script with Ajax Jquery. We have already discuss topic on search html data by using Ajax with Jquery and we have also discuss how to use Bootstrap Typeahead plugin for make autocomplete textbox with Ajax PHP. But now here we have seen combination of both that means we have we have learn how to integrate Bootstrap Typeahead plugin for search table data on server side PHP script with Ajax.

Bootstrap Typeahead plugin is used to make Autocomplete that means we have start to type in textbox then it drop down posible data according to what we have type in textbox. In short this plugin add autocomplete feature to any input type textbox to drop down hint to user while he start filling data in textbox. So here we have used this plugin for search table data with autocomplete textbox.

For make autocomplete search box for search HTML data by send Ajax request to PHP script. In this feature user can search any table column data. Here first we want to make autocomplete search textbox so for this we have use Bootstrap Typeahead plugin by using typeahead() method, by using this plugin we can make auto completed textbox like Google or any other social media site. Then after we have want to search table data according to hint given by this plugin, so here we have integrate search query in typeahead() method, so when this plugin return possible data from autocomplete textbox then it also display search or filter data on table also. This way we have use Bootstrap Typeahead plugin for search table data by using autocomplete input text.






Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>How to Search Table Data by Typehead with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
 </head>
 <body>
  <br /><br />
  <div class="container">
   <h2 align="center">How to Search Table Data by Typehead with PHP Ajax</h2>
   <br /><br />
   <label>Search Employee Details</label>
   <div id="search_area">
    <input type="text" name="employee_search" id="employee_search" class="form-control input-lg" autocomplete="off" placeholder="Type Employee Name" />
   </div>
   <br />
   <br />
   <div id="employee_data"></div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 load_data('');
 
 function load_data(query, typehead_search = 'yes')
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{query:query, typehead_search:typehead_search},
   success:function(data)
   {
    $('#employee_data').html(data);
   }
  });
 }
 
 $('#employee_search').typeahead({
  source: function(query, result){
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data){
     result($.map(data, function(item){
      return item;
     }));
     load_data(query, 'yes');
    }
   });
  }
 });
 
 $(document).on('click', 'li', function(){
  var query = $(this).text();
  load_data(query);
 });
 
});
</script>


fetch.php



<?php
//fetch.php
if(isset($_POST["query"]))
{
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $request = mysqli_real_escape_string($connect, $_POST["query"]);
 $query = "
  SELECT * FROM tbl_employee 
  WHERE name LIKE '%".$request."%' 
  OR gender LIKE '%".$request."%' 
  OR designation LIKE '%".$request."%'
 ";
 $result = mysqli_query($connect, $query);
 $data =array();
 $html = '';
 $html .= '
  <table class="table table-bordered table-striped">
   <tr>
    <th>Name</th>
    <th>Gender</th>
    <th>Designation</th>
   </tr>
  ';
 if(mysqli_num_rows($result) > 0)
 {
  while($row = mysqli_fetch_array($result))
  {
   $data[] = $row["name"];
   $data[] = $row["gender"];
   $data[] = $row["designation"];
   $html .= '
   <tr>
    <td>'.$row["name"].'</td>
    <td>'.$row["gender"].'</td>
    <td>'.$row["designation"].'</td>
   </tr>
   ';
  }
 }
 else
 {
  $data = 'No Data Found';
  $html .= '
   <tr>
    <td colspan="3">No Data Found</td>
   </tr>
   ';
 }
 $html .= '</table>';
 if(isset($_POST['typehead_search']))
 {
  echo $html;
 }
 else
 {
  $data = array_unique($data);
  echo json_encode($data);
 }
}

?>


Database



--
-- Database: `testing`
--

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

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

CREATE TABLE IF NOT EXISTS `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(30) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=latin1;

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

INSERT INTO `tbl_employee` (`id`, `name`, `gender`, `designation`) VALUES
(1, 'Micheal Bruce', 'Male', 'System Architect'),
(5, 'Clara Gilliam', 'Female', 'Programmer'),
(6, 'Robert L. Hoskins', 'Male', 'Personal secretary'),
(7, 'Walter M. Watkins', 'Male', 'Crane and tower operator'),
(8, 'Stanley L. Gomez', 'Male', 'HVACR technician'),
(9, 'Erik C. Parker', 'Male', 'Graduate teaching assistant'),
(11, 'Stephanie B. Boland', 'Female', 'Adjuster'),
(12, 'Donald P. Fitzgerald', 'Male', 'Pharmacy aide'),
(13, 'Angel Lewis', 'Female', 'Paper goods tender'),
(14, 'Justin Dean', 'Male', 'Magnetic resonance Technolist'),
(15, 'Nora Blake', 'Female', 'Neuroscience nurse'),
(16, 'Russell Fox', 'Male', 'Safe repairer'),
(17, 'Daryl Bradley', 'Female', 'Intructional coordinator'),
(18, 'Benjamin Gonzales', 'Male', 'Musician'),
(19, 'Viola Francis', 'Female', 'Amusement machine servicer'),
(20, 'Reginald Benson', 'Male', 'Management information systems'),
(21, 'Glenda Ray', 'Female', 'Business support assistant'),
(22, 'Paula Vargas', 'Female', 'Electrical engineer'),
(23, 'Mark Armstrong', 'Male', 'Merchandise manager'),
(24, 'Jaime Campbell', 'Female', 'Petroleum pump system operator'),
(25, 'Mike Beck', 'Male', 'Placement officer'),
(26, 'Ann Lowe', 'Female', 'Computer scientist');

--
-- 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=27;