Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, November 23, 2015

Select Insert Delete-JQuery AJAX PHP MySql

PHP-MySql-HTML5-Bootstrap-JQyery-CSS3
Bootstrap Responsive Table and Form

In this tutorial,User can insert record and the record display on page without refresh a page and user can also delete the record and the the record delete also without refresh a page.This can be done by using JQuery and AJAX.

Here i also used Bootstrap for responsive table and form.
Bootstrap : Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.You can download latest Bootstrap from here

Config.php 


<?php
    error_reporting(1);
    $host="localhost";//Server Name
    $username="root";//User Name
    $pass="";//Password
    $db="ajaxdemo";//Database Name
    $connect=mysql_connect($host,$username,$pass)or die(mysql_error());//Connect to MySql Server
    $dbselect=mysql_select_db($db,$connect)or die(mysql_error());//Select Database
?>

Javascript 


$(document).ready(function(){      
    $(document).on('submit','#ajax_form',function(){
        var formData = new FormData($(this)[0]);
        var url = "ajax.php";
        $.ajax({
        type: "POST",
        url: url,
        data: formData, 
        cache: false,
        contentType: false,
        processData: false,
        success: function(data)
        {
             $("#ajax_table").append($(data));
             $('#imagePreview').css({"background":"none"});
             $('#imagePreview').css({"display":"none"});
             $('#ajax_form')[0].reset();
        }
     });
    return false;
    });
  });

 $(document).ready(function(){ 
    $(function() {
    $('#ajax_table').on('click', 'td a.delete', function(){
    var element = $(this);
    var del_id = element.attr("data-id");
    var info = 'id=' + del_id;
        if(confirm("Are you sure you want to delete this?"))
        {
         $.ajax({
           type: "POST",
           url: "ajax_delete.php",
           data: info,
           success: function(){

         }
        });
          $(this).parents("tr").animate({ backgroundColor: "yellow" }, "slow")
          .animate({ opacity: "hide" }, "slow");
        }
    return false;
    });
    });
 });

$(function() {
    $("#image").on("change", function()
    {
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){ // set image data as background of div
                $("#imagePreview").css({"width":"50px","height":"50px","background-position":"center center","background-size":"cover","-webkit-box-shadow":"0 0 1px 1px rgba(0, 0, 0, .3)","display":"inline-block"});
                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
        }
    });
});

HTML FORM 


<!DOCTYPE html>
<html>
<head>
<title>Select Insert Delete PHP JQuery Ajax Mysql Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/javascript.js"> 
</script>
</head>
<body>
<center><h1><a href="http://wayto-php.blogspot.in/" target="new">Way To PHP</a></h1></center>
<div class="container">
  <form class="form-horizontal" role="form" method="post" id="ajax_form" name="ajax_form" enctype="multipart/form-data">
    <div class="form-group">
      <label class="control-label col-sm-4" for="name">First Name:</label>
      <div class="col-sm-4">
        <input type="text" class="form-control" id="first_name" placeholder="Enter First Name" name="first_name">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-4" for="name">Last Name:</label>
      <div class="col-sm-4">
        <input type="text" class="form-control" id="name" placeholder="Enter Last Name" name="last_name">
      </div>
    </div>    
    <div class="form-group">
      <label class="control-label col-sm-4" for="occupation">Occupation:</label>
      <div class="col-sm-4">
        <input type="text" class="form-control" id="occupation" placeholder="Enter Occupation" name="occupation">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-4" for="country">Country:</label>
      <div class="col-sm-4">
        <input type="text" class="form-control" id="country" placeholder="Enter Country" name="country">
      </div>
    </div>
 <div class="form-group">
      <label class="control-label col-sm-4" for="image">Image:</label>
      <div class="col-sm-4">
  <div id="imagePreview"></div>
        <input type="file" class="form-control" id="image" name="image">
      </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-5 col-sm-6">
        <button type="submit" class="btn btn-default" name="add" id="add">Add New Record</button>
      </div>
    </div>
  </form>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Ajax.php 


<?php
    include 'config.php';
    $target_dir = "uploads/";
    $file_name=$_FILES['image']['name'];
    $full_name = explode('.',$file_name);
    $file_name = time().'.'.$full_name[1]; //Replace Image name with Time
    $target_file = $target_dir . basename($file_name);
    $targetPath = "uploads/".$_FILES['image']['name'];
    $upload=move_uploaded_file($_FILES["image"]["tmp_name"],$target_file);
    extract($_POST);
    $sql=mysql_query("INSERT INTO `users`(first_name,last_name,occupation,country,image)VALUES('".$first_name."','".$last_name."','".$occupation."','".$country."','".$file_name."')");
    $id  = mysql_insert_id();
     if($sql)
     {    
        echo '<tr>
          <td>'.$first_name.'</td>
          <td>'.$last_name.'</td>
          <td>'.$occupation.'</td>
          <td>'.$country.'</td>
          <td><img src="'.$target_file.'" class="img-responsive" alt="Picture" width="50px" height="50px"></td>
          <td><a data-id='.$id.' class="delete" href="#" name="delete" id="delete">Delete</a></td>
        </tr>';
     }
?>

Ajax_delete.php 


<?php 
    include 'config.php';
    if($_POST['id']!="")
    {
        extract($_POST);
        $id=mysql_real_escape_string($id);
        $sel=mysql_query("SELECT * FROM `users` WHERE id='".$id."'");
        $row=mysql_fetch_array($sel);
        unlink("uploads/".$row['image']);
        $sql=mysql_query("DELETE FROM `users` WHERE id='".$id."'");
    }
?>
 

CLICK HERE FOR DOWNLOAD COMPLETE CODE...

Tuesday, November 10, 2015

Pagination Using PHP MySql


pagination-PHP-MySql-Responsive Table Bootstrap

For doing pagination We Sholud know that how many number of records are exits in Table.Then We can decide that how many records display on single page.(Record Per Page).Then we should know that how many needed for display total records.For that we divide Total number of records to Record per page, and we get the total pages to display total records.

CODE: 

<?php
include 'config.php';
$select=mysql_query("SELECT id FROM `pagination`");
$count=mysql_num_rows($select);
$page_limit=3;
$total_pages=ceil($count/$page_limit);
?>
<html>
<head>
<title>Pagination-PHP MySql</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
</head>
<body>
<center><h1><a href="http://wayto-php.blogspot.in/" target="new">Way To PHP</a></h1></center>
<table class="table table-bordered" style="margin-top:100px;width:80%;margin-left:10%;">
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Country</th>
      <th>Occupation</th>
    </tr>
  </thead>
  <tbody>
  <?php
      if(isset($_GET['page']))
    {
        $page=$_GET['page'];
    }
    else
    {
        $page=1;
    }
    $start = ($page-1) * $page_limit;
    $sql = "SELECT * FROM `pagination` LIMIT $start, $page_limit"; 
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) { 
?> 
    <tr>
      <td><?php echo $row['id']; ?></td>
      <td><?php echo $row['name']; ?></td>
      <td><?php echo $row['country']; ?></td>
      <td><?php echo $row['occupation']; ?></td>
    </tr>
    <?php } ?>
  </tbody>
</table>
<ul style="margin-left:45%;" class="pagination">
<?php for ($i=1; $i<=$total_pages; $i++) {  ?>
    <li style="display:inline; margin-left:8px; font-size:larger;"><a href="index.php?page=<?php echo $i; ?>"><?php echo $i; ?></a></li>
<?php } ?>  
   </ul>
</body>
</html>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.js"></script> 


CLICK HERE FOR DOWNLOAD COMPLETE CODE... 

 

 

Sunday, November 8, 2015

Image Upload PHP JQuery Ajax

JQuery
We Want to upload an image without refresh a page and that can possible by Ajax.Here we use the JQuery and Ajax to upload an image.
In this example user select an image and click on Upload button and the image displayed without refresh a page.


Ajax Image Upload JQuery PHP

HTML FORM 

<form name="image_form" id="image_form" action="" enctype="multipart/form-data" method="post" >
<input type="file" class="textbox" id="image" name="image" required>
<input type="submit" name="submit" value="Upload" id="upload">
</form>

JQUERY SCRIPT 


<script type="text/javascript"> 
$(document).ready(function (e) {
    $("#image_form").on('submit',(function(e) {
        e.preventDefault();
        $.ajax({
            url:"upload.php",
            type: "POST",
            data:  new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
            $("#display=").html(data);
            },
              error: function()
            {
            }            
       });
    }));
});
</script>

PHP SCRIPT 

<?php
    if(is_array($_FILES))
    {
        $target_dir = "images/";
        $file_name=$_FILES['image']['name'];
        $full_name = explode('.',$file_name);
        $file_name = time().'.'.$full_name[1]; //Replace Image name with Time
        $target_file = $target_dir . basename($file_name);
        $targetPath = "images/".$_FILES['image']['name'];
        if(move_uploaded_file($_FILES["image"]["tmp_name"],$target_file))
        {
?>
<img src="<?php echo $target_file; ?>" width="200px" height="200px" />
<?php
}
}
?>

CLICK HERE FOR DOWNLOAD COMPLETE CODE... 

Monday, October 19, 2015

Login Form PHP MySql JQuery

PHP-MySql-HTML5-jQuery-CSS3 
Login Form


We want to create a Login Form.In the login form the Session variable are used.

Session Variable: HTTP is a Stateless protocol.Session variables are used to store individual client’s information on web server for later use,  as web server does not know which client’s request to be respond because, HTTP address does not maintained state.

We can use session_start() Function for start the session;

config.php 

<?php
    session_start();
    error_reporting(1);
    $host="localhost";
    $username="root";
    $pass="";
    $db="blog_demo";
    $connect=mysql_connect($host,$username,$pass)or die(mysql_error());
    $dbselect=mysql_select_db($db,$connect)or die(mysql_error());
?>


HTML

<form id="login_form" method="post" name="login_form">
    <input class="textbox" id="email" name="email" placeholder="Enter Your Email" type="text" />
    <input class="textbox" id="password" name="password" placeholder="Enter Your Password" type="password" />
    <input id="login" name="login" type="submit" value="Login" /> 
</form>

JavaScript  

<script type="text/javascript">
jQuery( document ).ready(function() {
        $('#login').click(function()
        {
            jQuery("#login_form").validate({
            rules:
            {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true
                }
            },
            messages:
            {
                email:{
                    required: "Please enter an email",
                    email: "Please enter a valid email"
                },
                password: {
                    required: "Please provide a password"
                }
            },
            submitHandler: function(form) {
                $.ajax({
                type: "POST",
                url: "login_ajax.php",//Ajax Call to PHP file without refresh a page
                data: $("#login_form").serialize(),
                cache: false,
                beforeSend: function(){ $("#login").val('Connecting...');},
                success: function(data){
                if(data=='true')
                {
                    window.location.href = "success.php";//Redirect the page by jQuery
                }
                else{
                    $("#login_error").html(data);
                    $("#login").val('Login');  
                }
            }
            }); 
        }      
        });
    });
});
</script>

PHP Code

<?php
   include'includes/config.php'
   $email=$_POST['email'];
   $password=$_POST['password'];
   $sql ="SELECT * FROM user WHERE email='$email' and password='$password'";
   $select=mysql_query($sql);
   $count=mysql_num_rows($select);
   if($count==1)
   {    
        $row=mysql_fetch_array($select);
        $_SESSION['id']=$row['id'];
        $_SESSION['username']=$row['username'];
        $_SESSION['email']=$row['email'];
        echo 'true';    
    }
    else
    {
        echo 'Wrong Email id and Password';
    }
?>
JQuery Validation


JQuery Validation Wrong Email and Password

Login Success PHP-MySql-JQuery

If user submit the form with blank field then it gives the messages like "Please enter an email".If user submit with wrong details then it display a message "Wrong Email id and Password" by ajax functionality without refresh a page but if user submit with right details then it redirect the welcome page.