Friday, 26 February 2016

Dynamically Add / Remove input fields in PHP with Jquery Ajax







Read Also - How to Edit Dynamic HTML Field by using Ajax with PHP



Hello Friends this tutorial is relating to dynamically insert or delete  input html fields using Jquery Ajax with PHP MySql. User can insert more than one data at the same time. User can Add bulk data at same time. Data will be inserted with out page refresh because we use ajax function call for insert data. User can add more fields by clicking on add more button then new textbox will be appear on webpage with remove button. If user want to remove some field then it can be remove input fields on click on remove button. Now a days this functionality is very useful in web application.








Source Code


index.php


    <html>  
      <head>  
           <title>Dynamically Add or Remove input fields in PHP with JQuery</title>  
           <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>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <br />  
                <br />  
                <h2 align="center">Dynamically Add or Remove input fields in PHP with JQuery</h2>  
                <div class="form-group">  
                     <form name="add_name" id="add_name">  
                          <div class="table-responsive">  
                               <table class="table table-bordered" id="dynamic_field">  
                                    <tr>  
                                         <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>  
                                         <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                                    </tr>  
                               </table>  
                               <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                          </div>  
                     </form>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      var i=1;  
      $('#add').click(function(){  
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
      });  
      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });  
      $('#submit').click(function(){            
           $.ajax({  
                url:"name.php",  
                method:"POST",  
                data:$('#add_name').serialize(),  
                success:function(data)  
                {  
                     alert(data);  
                     $('#add_name')[0].reset();  
                }  
           });  
      });  
 });  
 </script>
   

name.php


    <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $number = count($_POST["name"]);  
 if($number > 0)  
 {  
      for($i=0; $i<$number; $i++)  
      {  
           if(trim($_POST["name"][$i] != ''))  
           {  
                $sql = "INSERT INTO tbl_name(name) VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";  
                mysqli_query($connect, $sql);  
           }  
      }  
      echo "Data Inserted";  
 }  
 else  
 {  
      echo "Please Enter Name";  
 }  
 ?> 
   

Tuesday, 23 February 2016

How to Load More Data using Ajax Jquery


In this post we are going to learn load more data using Ajax JQuery in PHP with MySql. This is very common feature which is used in big social networking site like facebook, twitter, youtube etc. In this feature data load without page refresh. Data load from database using Ajax function call. With Ajax function call it get data from database and display on front end without page refresh. This functionality is very useful in load data step by step without page refresh and pagination.



In this post, We have discuss one other category of pagination in which there is one load more jquery button when we have click on that button next page data has been load on the same page without page refresh. This is simple tutorial on load data using Ajax Jquery in PHP.


If you have seen some social media sites like Youtube Twitter and even Facebook has been using load more data features. All this sites are use this features in which they do not display pagination links on their website but they are use this load more data button so when we have click on that button they get next page data from database by using Ajax with PHP and append that data on same page by using Jqueyr. In this data has been loaded without page refresh. So In this tutorial, We have implement this feature like load more data on single click of button and from the database we will get data by using jQuery Ajax and PHP. In this tutorial we will discuss step by step load more data on button using Jquery with Ajax PHP.


Check Below Online Demo



Load More Data using Ajax Jquery


How to generate simple random password in php?
Create Simple Image using PHP

Source Code


index.php


Under this page we have load first data on this page and write Jquery and Ajax code for fetch next data on this page.



<?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $sql = "SELECT * FROM tbl_video LIMIT 2";  
 $result = mysqli_query($connect, $sql);  
 $video_id = '';  
?>  
<html>  
     <head>  
          <title></title>  
          <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>  
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
     </head>  
     <body>  
          <div class="container">  
               <br />  
               <br />  
               <br />  
               <div class="table-responsive">  
                    <h2 align="center">Load More Data using Ajax Jquery</h2><br />  
                    <table class="table table-bordered" id="load_data_table">  
                         <?php  
                         while($row = mysqli_fetch_array($result))  
                         {  
                         ?>  
                              <tr>  
                                   <td><?php echo $row["video_title"]; ?></td>  
                              </tr>  
                         <?php  
                              $video_id = $row["video_id"];  
                         }  
                         ?>  
                         <tr id="remove_row">  
                              <td><button type="button" name="btn_more" data-vid="<?php echo $video_id; ?>" id="btn_more" class="btn btn-success form-control">more</button></td>  
                         </tr>  
                    </table>  
               </div>  
          </div>  
     </body>  
</html>  
 <script>  
 $(document).ready(function(){  
      $(document).on('click', '#btn_more', function(){  
           var last_video_id = $(this).data("vid");  
           $('#btn_more').html("Loading...");  
           $.ajax({  
                url:"load_data.php",  
                method:"POST",  
                data:{last_video_id:last_video_id},  
                dataType:"text",  
                success:function(data)  
                {  
                     if(data != '')  
                     {  
                          $('#remove_row').remove();  
                          $('#load_data_table').append(data);  
                     }  
                     else  
                     {  
                          $('#btn_more').html("No Data");  
                     }  
                }  
           });  
      });  
 });  
 </script>


load_data.php


This page has fetch data from database. This page has been received ajax request from index page and fetch data from database and send back data to index page.



<?php  
$output = '';  
$video_id = '';  
sleep(1);  
$connect = mysqli_connect("localhost", "root", "", "testing");  
$sql = "SELECT * FROM tbl_video WHERE video_id > ".$_POST['last_video_id']." LIMIT 2";  
$result = mysqli_query($connect, $sql);  
if(mysqli_num_rows($result) > 0)  
{  
     while($row = mysqli_fetch_array($result))  
     {  
          $video_id = $row["video_id"];  
          $output .= '  
               <tbody>  
               <tr>  
                    <td>'.$row["video_title"].'</td>  
               </tr></tbody>';  
     }  
     $output .= '  
               <tbody><tr id="remove_row">  
                    <td><button type="button" name="btn_more" data-vid="'. $video_id .'" id="btn_more" class="btn btn-success form-control">more</button></td>  
               </tr></tbody>  
     ';  
     echo $output;  
}  
?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_video`
--

CREATE TABLE IF NOT EXISTS `tbl_video` (
  `video_id` int(11) NOT NULL AUTO_INCREMENT,
  `video_title` text NOT NULL,
  PRIMARY KEY (`video_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;

--
-- Dumping data for table `tbl_video`
--

INSERT INTO `tbl_video` (`video_id`, `video_title`) VALUES
(1, 'How to generate simple random password in php?\r\n'),
(2, 'Create Simple Image using PHP\r\n'),
(3, 'How to check Username availability in php and MySQL using Ajax Jquery\r\n'),
(4, 'How to Insert Watermark on to Image using PHP GD Library\r\n'),
(5, 'Make SEO Friendly / Clean Url in PHP using .htaccess\r\n'),
(6, 'Live Table Add Edit Delete using Ajax Jquery in PHP Mysql\r\n'),
(7, 'How to Export MySQL data to Excel in PHP - PHP Tutorial\r\n'),
(8, 'How to Load More Data using Ajax Jquery\r\n'),
(9, 'Dynamically Add / Remove input fields in PHP with Jquery Ajax\r\n'),
(10, 'Read Excel Data and Insert into Mysql Database using PHP\r\n'),
(11, 'How to Convert Currency using Google Finance in PHP\r\n'),
(12, 'Dynamically generate a select list with jQuery, AJAX & PHP\r\n'),
(13, 'How to get Multiple Checkbox values in php\r\n'),
(14, 'Ajax Live Data Search using Jquery PHP MySql\r\n'),
(15, 'Auto Save Data using Ajax, Jquery, PHP and Mysql\r\n'),
(16, 'How to Use Ajax with PHP for login with shake effect\r\n'),
(17, 'Facebook style time ago function using PHP\r\n'),
(18, 'Upload Resize Image using Ajax Jquery PHP without Page Refresh\r\n\r\n'),
(19, 'How to Search for Exact word match FROM String using RLIKE\r\n'),
(20, 'How To Create A Show Hide Password Button using Jquery\r\n');

Tuesday, 16 February 2016

How to Export MySQL data to Excel in PHP - PHP Tutorial


This tutorial will learn you How to export Mysql data from web application to Excel file using PHP programming language. This functionality is mostly required in enterprise level web application. There are lots of data are transfer on daily basis and manage that into separate excel file. So, at that time this type of functionality is required in web application. This functionality reduce lots of time to take data into excel file.


In this simple post we have learn something regarding how to export data to Excel in PHP. If you have developed any project then that project you have to required this functionality like Exporting Data to Excel Sheet. So we have developed this tutorial, in which we have make simple PHP Script for Export Data from Web to Excel.



Online Demo


Export MySQL data to Excel in PHP


Name Address City Postal Code Country
Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la Construction 2222 Mexico D.F. 5021 Mexico
Antonio Moreno Mataderos 2312 Mexico D.F. 5023 Mexico
Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil


Source Code



<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$sql = "SELECT * FROM tbl_customer";  
$result = mysqli_query($connect, $sql);
?>
<html>  
 <head>  
  <title>Export MySQL data to Excel in PHP</title>  
  <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>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
 </head>  
 <body>  
  <div class="container">  
   <br />  
   <br />  
   <br />  
   <div class="table-responsive">  
    <h2 align="center">Export MySQL data to Excel in PHP</h2><br /> 
    <table class="table table-bordered">
     <tr>  
                         <th>Name</th>  
                         <th>Address</th>  
                         <th>City</th>  
       <th>Postal Code</th>
       <th>Country</th>
                    </tr>
     <?php
     while($row = mysqli_fetch_array($result))  
     {  
        echo '  
       <tr>  
         <td>'.$row["CustomerName"].'</td>  
         <td>'.$row["Address"].'</td>  
         <td>'.$row["City"].'</td>  
         <td>'.$row["PostalCode"].'</td>  
         <td>'.$row["Country"].'</td>
       </tr>  
        ';  
     }
     ?>
    </table>
    <br />
    <form method="post" action="export.php">
     <input type="submit" name="export" class="btn btn-success" value="Export" />
    </form>
   </div>  
  </div>  
 </body>  
</html>


export.php



<?php  
//export.php  
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
if(isset($_POST["export"]))
{
 $query = "SELECT * FROM tbl_customer";
 $result = mysqli_query($connect, $query);
 if(mysqli_num_rows($result) > 0)
 {
  $output .= '
   <table class="table" bordered="1">  
                    <tr>  
                         <th>Name</th>  
                         <th>Address</th>  
                         <th>City</th>  
       <th>Postal Code</th>
       <th>Country</th>
                    </tr>
  ';
  while($row = mysqli_fetch_array($result))
  {
   $output .= '
    <tr>  
                         <td>'.$row["CustomerName"].'</td>  
                         <td>'.$row["Address"].'</td>  
                         <td>'.$row["City"].'</td>  
       <td>'.$row["PostalCode"].'</td>  
       <td>'.$row["Country"].'</td>
                    </tr>
   ';
  }
  $output .= '</table>';
  header('Content-Type: application/xls');
  header('Content-Disposition: attachment; filename=download.xls');
  echo $output;
 }
}
?>

Sunday, 14 February 2016

Live Table Add Edit Delete using Ajax Jquery in PHP Mysql




Latest Post - Live Add Edit Delete Datatables Records using PHP Ajax


Hello Friends, In this tutorial we are going to learn how to live table Insert, Update, Delete and Fetch data from mysql database using Ajax Jquery in PHP programming language. For this feature I am using html5 contenteditable attribute. With the help of this contenteditable attribute table column will be editable and user can change live table data on single click. I am using Ajax call function for Insert data, update data, delete data and Select data from database. This all things are done on user end without page refresh. Ajax get request from user on front-end and send request to database using php language and done operation at back end and send back request to user without page refresh. This feature is very helpful. I hope this tutorial will help to all.






<div id="live_data"></div>

This is main page on which we have load data, so on this page first we have define one div tag with attribute "id=live_data", we will load data under this tag by using Ajax Jquery code and it will use attribute id as selector in Jquery code.

      function fetch_data()  
      {  
           $.ajax({  
                url:"select.php",  
                method:"POST",  
                success:function(data){  
                     $('#live_data').html(data);  
                }  
           });  
      } 

Then after make this jquery function, which fetch data from table and converted in table format and then after display under div tag with attribute "id=live_data", under this function, it use Ajax method for fetch data from server and display on web page. This function send request to this select.php page.

<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $output = '';  
 $sql = "SELECT * FROM tbl_sample 

ORDER BY id DESC";  
 $result = mysqli_query($connect, $sql);  
 $output .= '  
      <div class="table-responsive">  
           <table class="table table-bordered">  
                <tr>  
                     <th width="10%">Id</th>  
                     <th width="40%">First Name</th>  
                     <th width="40%">Last Name</th>  
                     <th width="10%">Delete</th>  
                </tr>';  
 if(mysqli_num_rows($result) > 0)  
 {  
      while($row = 

mysqli_fetch_array($result))  
      {  
           $output .= '  
                <tr>  
                     <td>'.

$row["id"].'</td>  
                     <td class="first_name" data-id1="'.$row["id"].'" contenteditable>'.$row["first_name"].'</td>  
                     <td class="last_name" data-id2="'.$row["id"].'" contenteditable>'.$row["last_name"].'</td>  
                     <td><button type="button" name="delete_btn" data-

id3="'.$row["id"].'" class="btn btn-xs btn-

danger btn_delete">x</button></td>  
                </tr>  
           ';  
      }  
      $output .= '  
           <tr>  
                <td></td>  
                <td id="first_name" contenteditable></td>  
                <td id="last_name" contenteditable></td>  
                <td><button type="button" name="btn_add" id="btn_add" 

class="btn btn-xs btn-success">+</button></td>  
           </tr>  
      ';  
 }  
 else  
 {  
      $output .= '<tr>  
                          <td colspan="4">Data not Found</td>  
                     </tr>';  
 }  
 $output .= '</table>  


      </div>';  
 echo $output;  
 ?>

This php code write on select.php page, because fetch_data() jquery function send request to this page, on this page it will fetch data from table and then convert that data into HTML Table format and send back to fetch_data() function.

You can see under while loop we have store data in table format, in first <td> tag it will store id, in second and third <td> tag attribute we have define class, in second have write class="first_name" and in third we have write class="last_name", we will use this attribute class in jquery code for live edit or update of table data.





Then after in both tag we have also add data attribute tag with two different name. In this tag we have store id of data, value of this data attribute we will use in jquery code while live updating of data.

In Both tag we have also use one more HTML attribute like contenteditable, by using this attribute we can live change the text or value this <td> tag. So this way we have define different attribute in second and third <td> tag.

In Fourth <td> tag we have define delete button for removing live data without page refresh, Under this delete button we have store unique id in data attribute, value of this data attribute we can fetch in Jquery code while live remove or delete of particular records. In this button tag we have add on class="btn_delete". We will use this class as selector in Jquery code.





In this code in outside of while loop we have also define one table row with four <td> tag, in second and third <td> tag we have define unique id attribute to both tag. We have use this id attribute as selector in JQuery code and by using this id we can get the text of <td> tag in Jquery code. In both <td> tag we have write one more attribute like contenteditable, by using this attribute we can live edit the text of this tag. In last <td> tag we have define one button for Add new live records, in that button we have use id attribute for selector in JQuery code. We will write Jquery code for Live Insert or Add new records on this button.


fetch_data();

So In backend our code is ready for fetching data and we have already make jquery function for load data on we page, so we have called this function, so when page load, this function will be called and it will load data on web page in HTML Table format.

      $(document).on('click', '#btn_add', function(){  
           var first_name = $('#first_name').text();  
           var last_name = $('#last_name').text();  
           if(first_name == '')  
           {  
                alert("Enter First Name");  
                return false;  
           }  
           if(last_name == '')  
           {  
                alert("Enter Last Name");  
                return false;  
           }  
           $.ajax({  
                url:"insert.php",  
                method:"POST",  
                data:{first_name:first_name, last_name:last_name},  
                dataType:"text",  
                success:function(data)  
                {  
                     alert(data);  
                     fetch_data();  
                }  
           })  
      });

This JQuery code is for Live Insert or Add of Data into Mysql Table. We have write Jquery code on Button with id="btn_add" on click event. When we have click on This button then it will Insert data into table. Under this first we have fetch text from <td> tag by selecting attribute id. After fetching value from <td> tag then it will check both variable has some value or not. If both value has some value then it will make Ajax request and send to insert.php page. With Ajax request it will send value of both <td> tag to server. After successfully request send and received it will reload table data by calling fetch_data() function.

<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $sql = "INSERT INTO tbl_sample(first_name, last_name) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";  
 if(mysqli_query($connect, $sql))  
 {  
      echo 'Data Inserted';  
 }  
 ?>

This is php code written on insert.php page, This page will received data from Ajax request and on this page it will make Insert Query for Inserting or Adding data into Mysql Table and it will send respond to Ajax request by write echo statement.

      function edit_data(id, text, column_name)  
      {  
           $.ajax({  
                url:"edit.php",  
                method:"POST",  
                data:{id:id, text:text, column_name:column_name},  
                dataType:"text",  
                success:function(data){  
                     alert(data);  
                }  
           });  
      }

After Successfully Live Insert or Add data, now we want to edit data, so in Jquery code we have make this edit_data(id, text, column_name) function with three argument. Value of All argument data has been send to edit.php page.

<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $id = $_POST["id"];  
 $text = $_POST["text"];  
 $column_name = $_POST["column_name"];  
 $sql = "UPDATE tbl_sample SET ".$column_name."='".$text."' WHERE id='".$id."'";  
 if(mysqli_query($connect, $sql))  
 {  
      echo 'Data Updated';  
 }  
 ?>

Above code is written under edit.php page, and this page will received data from Ajax request and then after it will make Update query and execute query and update particular id of data in Mysql Table.

      $(document).on('blur', '.first_name', function(){  
           var id = $(this).data("id1");  
           var first_name = $(this).text();  
           edit_data(id, first_name, "first_name");  
      });

Above Jquery code is write for Live Update or Edit of table column first_name, We have write JQuery code on <td> tag with class selector on blur event, So when we have leave first_name <td> tag then this code will execute. Under this function it will received id from data-id1 attribute and text of first name get from <td> class attribute with text() method. This method will fetch text from <td> tag and store into one variable. Then after we have called edit_data() function which send Ajax request to edit.php page and then after it will update or edit first_name table column data.

      $(document).on('blur', '.last_name', function(){  
           var id = $(this).data("id2");  
           var last_name = $(this).text();  
           edit_data(id,last_name, "last_name");  
      });

Above Jquery code is write for Live Update or Edit of table column last_name, We have write JQuery code on <td> tag with class selector on blur event, So when we have leave last_name <td> tag then this code will execute. Under this function it will received id from data-id2 attribute and text of last name get from <td> class attribute with text() method. This method will fetch text from <td> tag and store into one variable. Then after we have called edit_data() function which send Ajax request to edit.php page and then after it will update or edit last_name table column data.

      $(document).on('click', '.btn_delete', function(){  
           var id=$(this).data("id3");  
           if(confirm("Are you sure you want to delete this?"))  
           {  
                $.ajax({  
                     url:"delete.php",  
                     method:"POST",  
                     data:{id:id},  
                     dataType:"text",  
                     success:function(data){  
                          alert(data);  
                          fetch_data();  
                     }  
                });  
           }  
      });  

Above JQuery code is write for Live Delete or Remove Mysql table data. We have write JQuery code on button with class="btn_delete", we have use this class as selector in this Jquery code, so When we have click on delete button then this code will execute. Under this first we have get id from button attribute data-id3. In which we have store unique id. Then after it has send Ajax request to delete.php page. With Ajax request it has been send value of id variable to delete.php page. In Ajax request it will received respond from server and then after it has called fetch_data() functio for refresh table table on web page.

<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $sql = "DELETE FROM tbl_sample WHERE id = '".$_POST["id"]."'";  
 if(mysqli_query($connect, $sql))  
 {  
      echo 'Data Deleted';  
 }  
 ?>

Above PHP Code is written on delete.php page. This page has been received data from Ajax request and then after it will delete query and remove or delete data from Mysql Table and send respond to Ajax method.






So this is my sample code for making system like Live table Insert Update Delete and Fetch of Mysql Table data by using PHP Script with Ajax JQuery method. This is a single page web application. You can perform all operation on single page without going to another page. If you have any query or inputs, just comment your query or inputs in comment box. We will help you.

Complete Source Code


index.php


<html>  
      <head>  
           <title>Live Table Data Edit</title>  
           <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>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <br />  
                <br />  
                <br />  
                <div class="table-responsive">  
                     <h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />  
                     <div id="live_data"></div>                 
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      function fetch_data()  
      {  
           $.ajax({  
                url:"select.php",  
                method:"POST",  
                success:function(data){  
                     $('#live_data').html(data);  
                }  
           });  
      }  
      fetch_data();  
      $(document).on('click', '#btn_add', function(){  
           var first_name = $('#first_name').text();  
           var last_name = $('#last_name').text();  
           if(first_name == '')  
           {  
                alert("Enter First Name");  
                return false;  
           }  
           if(last_name == '')  
           {  
                alert("Enter Last Name");  
                return false;  
           }  
           $.ajax({  
                url:"insert.php",  
                method:"POST",  
                data:{first_name:first_name, last_name:last_name},  
                dataType:"text",  
                success:function(data)  
                {  
                     alert(data);  
                     fetch_data();  
                }  
           })  
      });  
      function edit_data(id, text, column_name)  
      {  
           $.ajax({  
                url:"edit.php",  
                method:"POST",  
                data:{id:id, text:text, column_name:column_name},  
                dataType:"text",  
                success:function(data){  
                     alert(data);  
                }  
           });  
      }  
      $(document).on('blur', '.first_name', function(){  
           var id = $(this).data("id1");  
           var first_name = $(this).text();  
           edit_data(id, first_name, "first_name");  
      });  
      $(document).on('blur', '.last_name', function(){  
           var id = $(this).data("id2");  
           var last_name = $(this).text();  
           edit_data(id,last_name, "last_name");  
      });  
      $(document).on('click', '.btn_delete', function(){  
           var id=$(this).data("id3");  
           if(confirm("Are you sure you want to delete this?"))  
           {  
                $.ajax({  
                     url:"delete.php",  
                     method:"POST",  
                     data:{id:id},  
                     dataType:"text",  
                     success:function(data){  
                          alert(data);  
                          fetch_data();  
                     }  
                });  
           }  
      });  
 });  
 </script>

select.php



<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $output = '';  
 $sql = "SELECT * FROM tbl_sample ORDER BY id DESC";  
 $result = mysqli_query($connect, $sql);  
 $output .= '  
      <div class="table-responsive">  
           <table class="table table-bordered">  
                <tr>  
                     <th width="10%">Id</th>  
                     <th width="40%">First Name</th>  
                     <th width="40%">Last Name</th>  
                     <th width="10%">Delete</th>  
                </tr>';  
 if(mysqli_num_rows($result) > 0)  
 {  
      while($row = mysqli_fetch_array($result))  
      {  
           $output .= '  
                <tr>  
                     <td>'.$row["id"].'</td>  
                     <td class="first_name" data-id1="'.$row["id"].'" contenteditable>'.$row["first_name"].'</td>  
                     <td class="last_name" data-id2="'.$row["id"].'" contenteditable>'.$row["last_name"].'</td>  
                     <td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>  
                </tr>  
           ';  
      }  
      $output .= '  
           <tr>  
                <td></td>  
                <td id="first_name" contenteditable></td>  
                <td id="last_name" contenteditable></td>  
                <td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>  
           </tr>  
      ';  
 }  
 else  
 {  
      $output .= '<tr>  
                          <td colspan="4">Data not Found</td>  
                     </tr>';  
 }  
 $output .= '</table>  
      </div>';  
 echo $output;  
 ?>

insert.php


<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $sql = "INSERT INTO tbl_sample(first_name, last_name) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";  
 if(mysqli_query($connect, $sql))  
 {  
      echo 'Data Inserted';  
 }  
 ?> 

edit.php


<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $id = $_POST["id"];  
 $text = $_POST["text"];  
 $column_name = $_POST["column_name"];  
 $sql = "UPDATE tbl_sample SET ".$column_name."='".$text."' WHERE id='".$id."'";  
 if(mysqli_query($connect, $sql))  
 {  
      echo 'Data Updated';  
 }  
 ?>

delete.php


<?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $sql = "DELETE FROM tbl_sample WHERE id = '".$_POST["id"]."'";  
 if(mysqli_query($connect, $sql))  
 {  
      echo 'Data Deleted';  
 }  
 ?>

Wednesday, 10 February 2016

Make SEO Friendly / Clean Url in PHP using .htaccess



In this tutorial I will show you how to make seo friendly or clean url in PHP programming language using apache .htaccess file. Semantic Url is one of the required things for Content Marketing. With the help of pretty url our website content will be Indexed on different search engine very fast. Clean Url is one part of Search Engine Optimization. SEO Friendly Url  will increase our ranking on different search engine. With the help of this clean slug our presence on search engine will increase. So, How to gain this feature for our ecommerce website, these all things are learn in this video. I think you will learn this things from this video.



Table Structure


 CREATE TABLE IF NOT EXISTS `tbl_post` (  
  `post_id` int(11) NOT NULL AUTO_INCREMENT,  
  `post_title` text NOT NULL,  
  `post_text` text NOT NULL,  
  `post_url` text NOT NULL,  
  PRIMARY KEY (`post_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  

index.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 if(isset($_POST["submit_btn"]))  
 {  
      $post_title = mysqli_real_escape_string($connect, $_POST["post_title"]);  
      $post_text = mysqli_real_escape_string($connect, $_POST["post_text"]);  
      $post_title = htmlentities($post_title);  
      $post_text = htmlentities($post_text);  
      $sql = "INSERT INTO tbl_post (post_title, post_text, post_url) VALUES ('".$post_title."', '".$post_text."', '".php_slug($post_title)."')";  
      if(mysqli_query($connect, $sql))  
      {  
           header("location:post/".php_slug($post_title)."");  
      }  
 }  
 function php_slug($string)  
 {  
      $slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($string)));  
      return $slug;  
 }  
 ?>  
 <html>  
      <head>  
           <title>Make SEO Friendly / Clean Url in PHP using .htaccess</title>  
           <style>  
           .container  
           {  
                width:700px;  
                margin:0 auto;  
                border:1px solid #ccc;  
                padding:16px;  
           }  
           .form_text  
           {  
                width:100%;  
                padding:6px;  
           }  
           </style>  
      </head>  
      <body>  
           <div class="container">  
                <h3 align="center">Make SEO Friendly / Clean Url in PHP using .htaccess</h3>  
                <form name="submit_form" method="post">  
                     <p>Post Title  
                     <input type="text" name="post_title" class="form_text" maxlength="200" />  
                     </p>  
                     <p>Post Text  
                     <textarea name="post_text" class="form_text" rows="10"></textarea>  
                     </p>  
                     <p><input type="submit" name="submit_btn" value="Submit" />  
                </form>  
           </div>  
      </body>  
 </html>  

post.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $post_url = $_GET["post_url"];  
 $sql = "SELECT * FROM tbl_post WHERE post_url = '".$post_url."'";  
 $result = mysqli_query($connect, $sql);  
 ?>  
 <html>  
      <head>  
           <title>Make SEO Friendly / Clean Url in PHP using .htaccess</title>  
           <style>  
           .container  
           {  
                width:700px;  
                margin:0 auto;  
                border:1px solid #ccc;  
                padding:16px;  
           }  
           .form_text  
           {  
                width:100%;  
                padding:6px;  
           }  
           </style>  
      </head>  
      <body>  
           <div class="container">  
                <h3 align="center">Make SEO Friendly / Clean Url in PHP using .htaccess</h3>  
                <?php  
                if(mysqli_num_rows($result) > 0)  
                {  
                     while($row = mysqli_fetch_array($result))  
                     {  
                          echo '<h3>'.$row["post_title"].'</h3>';  
                          echo '<p>'.$row["post_text"].'</p>';  
                     }  
                }  
                else  
                {  
                     echo '404 Page';  
                }  
                ?>  
           </div>  
      </body>  
 </html>  

.htaccess File


 RewriteEngine On  
 RewriteRule ^post/([a-zA-Z0-9-/]+)$ post.php?post_url=$1  
 RewriteRule ^post/([a-zA-Z-0-9-]+)/ post.php?post_url=$1  

Thursday, 4 February 2016

How to Insert Watermark on to Image using PHP GD Library



Hello Friends, In this tutorial we are going to learn how can we insert watermark or watertext or website link on to an Image. Because in most of the ecommerce website we can see the product image with watermark or watertext present on that image. So, I make this useful tutorial with video.

Before going to start with PHP GD Library, First we have to enable php_gd2 PHP extension.

I will use following function for Insert watermark.

  • imagecreatefrompng(image) — Create a new image from given image
  • imagesx(image) - Return the width of Given Image
  • imagesy(image) - Return the height of given image
  • imagettftext(image source, font size, angle, x axis, y axis, text color, font path, watermar text) - Add text on to image
  • imagepng(image) - create png image
  • imagedestroy(image) - destroy image

Now first I make function with name insert watermark.

 function insert_watermark()  

I have one image with name image.png.


How to Insert Watermark on to Image using PHP GD Library


Now I store this into one image variable with the help of imagecreatefrompng() function. This function create image from png image file.

 $image = imagecreatefrompng("image.png");  

Then after I define text color using imagecolorallocate() function. In this function first parameter is image source and other parameter is value of RGB color.

 $textcolor = imagecolorallocate($image, 255, 255, 255);  

After define text color I want to proceed for insert text on to image. For this I will use imagettftext() function. With the help of this function we can control over the font size. For this function I have to download font and store in our working folder.

After storing font under working folder, I start using this imagettftext() function. In this function first parameter is image source, second parameter is angle of text, third is x axis, forth is y axis, fifth is text color, text color which I have define earlier in this code, sixth is font path and last is water mark text.

 imagettftext($image, 14, 0, imagesx($image)-125, imagesy($image)-20, $textcolor, 'arial.ttf', "Webslesson");  

After defining text to image I have define content type by using header() function.

 header("Content-type: image/png");  

After defining content type I have to define type of image by using imagepng() function.

 imagepng($image);  

And Lastly I want to destroy image for clear memory, I have to use imagedestroy() function.

 imagedestroy($image);  

Now Finally I have make function for add watermark text on to a image.

 <?php  
 function insert_watermark()  
 {  
      $image = imagecreatefrompng("image.png");  
      $textcolor = imagecolorallocate($image, 255, 255, 255);  
      imagettftext($image, 14, 0, imagesx($image)-125, imagesy($image)-20, $textcolor, 'arial.ttf', "Webslesson");  
      header("Content-type: image/png");  
      imagepng($image);  
      imagedestroy($image);       
 }  
 ?>  

Now I use this function and insert watermark on to a image by simple echo statement.

 echo '<img src="'.insert_watermark().'" />';  

Monday, 1 February 2016

How to check Username availability in php and MySQL using Ajax Jquery



Hi, If you are looking for web tutorial on how to check Username is available or not, So In this post, you can simple PHP script to check username availability using ajax in php with JQuery and Mysql. This type of feature is most common and you can see most of the available online website. This is very easy to understand and in this post we have write simple PHP Code that Live check username already exists or not by using PHP with Ajax.


Here when you have start registration then at that it will ask you username, so when you have enter username, at that time an Ajax function has called to server for check entered username is unique or not. At server side it will check into database and find entered username is available or not. After this it will send back to Ajax request regarding username availability or not and it will display result live without refreshing of page. So in simple word this tutorial is based on Ajax username validation in PHP. In this post you can also find live Demo and source code also.

Online Demo


username - mike


Live Username Available or not in PHP using Ajax Jquery









Source Code


index.php



<html>  
 <head>  
  <title>Live Username Available or not By using PHP Ajax Jquery</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>  
  <style>  
  body  
  {  
   margin:0;  
   padding:0;  
   background-color:#f1f1f1;  
  }  
  .box  
  {  
   width:800px;  
   border:1px solid #ccc;  
   background-color:#fff;  
   border-radius:5px;
   margin-top:36px;  
  }  
  </style>  
 </head>  
 <body>  
  <div class="container box">  
   <div class="form-group">  
    <h3 align="center">Live Username Available or not By using PHP Ajax Jquery</h3><br />  
    <label>Enter Username</label>  
    <input type="text" name="username" id="username" class="form-control" />
    <span id="availability"></span>
    <br /><br />
    <button type="button" name="register" class="btn btn-info" id="register" disabled>Register</button>
    <br />
   </div>  
   <br />  
   <br />  
  </div>  
 </body>  
</html>  
<script>  
 $(document).ready(function(){  
   $('#username').blur(function(){

     var username = $(this).val();

     $.ajax({
      url:'check.php',
      method:"POST",
      data:{user_name:username},
      success:function(data)
      {
       if(data != '0')
       {
        $('#availability').html('<span class="text-danger">Username not available</span>');
        $('#register').attr("disabled", true);
       }
       else
       {
        $('#availability').html('<span class="text-success">Username Available</span>');
        $('#register').attr("disabled", false);
       }
      }
     })

  });
 });  
</script>


check.php



<?php  
//check.php  
$connect = mysqli_connect("localhost", "root", "", "testing"); 
if(isset($_POST["user_name"]))
{
 $username = mysqli_real_escape_string($connect, $_POST["user_name"]);
 $query = "SELECT * FROM users WHERE username = '".$username."'";
 $result = mysqli_query($connect, $query);
 echo mysqli_num_rows($result);
}
?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(250) NOT NULL,
  `password` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `password`) VALUES
(1, 'mike', '5f4dcc3b5aa765d61d8327deb882cf99');