Friday, 16 February 2018

Ajax Multiple Image Upload with Edit Delete using PHP Mysql



In this you can find not only how to upload multiple image or file without submit form using Ajax Jquery with PHP but also you can learn how to edit or update image information in database and folder also and delete or remove image from folder and from database also. In this one topic we have covered multiple topic, so you can learn lots of things from this single post. In one of our tutorial we have already discuss how to upload singe file without submit form using PHP with Ajax Jquery. But here we have upload multiple images with our using form submit event by using Ajax JQuery as front end and PHP and Mysql s back end.

When Multiple Images uploaded into folder then after we have insert uploaded images details like image name and description in table. So every uploaded image data will be inserted into Mysql table. After uploading image we have by using Ajax function fetch image details from Mysql table and display on web page in table format with edit and delete button. This all upload of multiple image and after that inserting of uploaded images data into mysql table process has been done without refresh of web page because we have use Ajax for this things with PHP and Mysql.

After successfully upload of image with data inserted into Mysql table. Now suppose we want to edit or update some details like image name or image description then this things we have also done by using Bootstrap modal. When we have click on edit button then that particular images details has been come with pop up Bootstrap Modal. Here we can not only change image name in Mysql table but also it will change image name in folder also. Same way in delete or remove operation it will not only remove image data from Mysql table but also it has remove or delete image from folder also. Here this all process has been done without refresh of web page because we have use Ajax Jquery with PHP Mysql. In short, In this post we have done insert update delete multiple image in PHP with Mysql.






Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Ajax Multiple Image Upload with Edit Delete using PHP Mysql</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">Ajax Multiple Image Upload with Edit Delete using PHP Mysql</h3>
   <br />
   <div align="right">
    <input type="file" name="multiple_files" id="multiple_files" multiple />
    <span class="text-muted">Only .jpg, png, .gif file allowed</span>
    <span id="error_multiple_files"></span>
   </div>
   <br />
   <div class="table-responsive" id="image_table">
    
   </div>
  </div>
 </body>
</html>
<div id="imageModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="POST" id="edit_image_form">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">&times;</button>
     <h4 class="modal-title">Edit Image Details</h4>
    </div>
    <div class="modal-body">
     <div class="form-group">
      <label>Image Name</label>
      <input type="text" name="image_name" id="image_name" class="form-control" />
     </div>
     <div class="form-group">
      <label>Image Description</label>
      <input type="text" name="image_description" id="image_description" class="form-control" />
     </div>
    </div>
    <div class="modal-footer">
     <input type="hidden" name="image_id" id="image_id" value="" />
     <input type="submit" name="submit" class="btn btn-info" value="Edit" />
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
   </form>
  </div>
 </div>
</div>
<script>
$(document).ready(function(){
 load_image_data();
 function load_image_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#image_table').html(data);
   }
  });
 } 
 $('#multiple_files').change(function(){
  var error_images = '';
  var form_data = new FormData();
  var files = $('#multiple_files')[0].files;
  if(files.length > 10)
  {
   error_images += 'You can not select more than 10 files';
  }
  else
  {
   for(var i=0; i<files.length; i++)
   {
    var name = document.getElementById("multiple_files").files[i].name;
    var ext = name.split('.').pop().toLowerCase();
    if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
    {
     error_images += '<p>Invalid '+i+' File</p>';
    }
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("multiple_files").files[i]);
    var f = document.getElementById("multiple_files").files[i];
    var fsize = f.size||f.fileSize;
    if(fsize > 2000000)
    {
     error_images += '<p>' + i + ' File Size is very big</p>';
    }
    else
    {
     form_data.append("file[]", document.getElementById('multiple_files').files[i]);
    }
   }
  }
  if(error_images == '')
  {
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){
     $('#error_multiple_files').html('<br /><label class="text-primary">Uploading...</label>');
    },   
    success:function(data)
    {
     $('#error_multiple_files').html('<br /><label class="text-success">Uploaded</label>');
     load_image_data();
    }
   });
  }
  else
  {
   $('#multiple_files').val('');
   $('#error_multiple_files').html("<span class='text-danger'>"+error_images+"</span>");
   return false;
  }
 });  
 $(document).on('click', '.edit', function(){
  var image_id = $(this).attr("id");
  $.ajax({
   url:"edit.php",
   method:"post",
   data:{image_id:image_id},
   dataType:"json",
   success:function(data)
   {
    $('#imageModal').modal('show');
    $('#image_id').val(image_id);
    $('#image_name').val(data.image_name);
    $('#image_description').val(data.image_description);
   }
  });
 }); 
 $(document).on('click', '.delete', function(){
  var image_id = $(this).attr("id");
  var image_name = $(this).data("image_name");
  if(confirm("Are you sure you want to remove it?"))
  {
   $.ajax({
    url:"delete.php",
    method:"POST",
    data:{image_id:image_id, image_name:image_name},
    success:function(data)
    {
     load_image_data();
     alert("Image removed");
    }
   });
  }
 }); 
 $('#edit_image_form').on('submit', function(event){
  event.preventDefault();
  if($('#image_name').val() == '')
  {
   alert("Enter Image Name");
  }
  else
  {
   $.ajax({
    url:"update.php",
    method:"POST",
    data:$('#edit_image_form').serialize(),
    success:function(data)
    {
     $('#imageModal').modal('hide');
     load_image_data();
     alert('Image Details updated');
    }
   });
  }
 }); 
});
</script>


database_connection.php



<?php

//database_connection.php

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

?>


fetch.php



<?php
include('database_connection.php');
$query = "SELECT * FROM tbl_image ORDER BY image_id DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$number_of_rows = $statement->rowCount();
$output = '';
$output .= '
 <table class="table table-bordered table-striped">
  <tr>
   <th>Sr. No</th>
   <th>Image</th>
   <th>Name</th>
   <th>Description</th>
   <th>Edit</th>
   <th>Delete</th>
  </tr>
';
if($number_of_rows > 0)
{
 $count = 0;
 foreach($result as $row)
 {
  $count ++; 
  $output .= '
  <tr>
   <td>'.$count.'</td>
   <td><img src="files/'.$row["image_name"].'" class="img-thumbnail" width="100" height="100" /></td>
   <td>'.$row["image_name"].'</td>
   <td>'.$row["image_description"].'</td>
   <td><button type="button" class="btn btn-warning btn-xs edit" id="'.$row["image_id"].'">Edit</button></td>
   <td><button type="button" class="btn btn-danger btn-xs delete" id="'.$row["image_id"].'" data-image_name="'.$row["image_name"].'">Delete</button></td>
  </tr>
  ';
 }
}
else
{
 $output .= '
  <tr>
   <td colspan="6" align="center">No Data Found</td>
  </tr>
 ';
}
$output .= '</table>';
echo $output;
?>


upload.php



<?php
//upload.php
include('database_connection.php');
if(count($_FILES["file"]["name"]) > 0)
{
 //$output = '';
 sleep(3);
 for($count=0; $count<count($_FILES["file"]["name"]); $count++)
 {
  $file_name = $_FILES["file"]["name"][$count];
  $tmp_name = $_FILES["file"]['tmp_name'][$count];
  $file_array = explode(".", $file_name);
  $file_extension = end($file_array);
  if(file_already_uploaded($file_name, $connect))
  {
   $file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
  }
  $location = 'files/' . $file_name;
  if(move_uploaded_file($tmp_name, $location))
  {
   $query = "
   INSERT INTO tbl_image (image_name, image_description) 
   VALUES ('".$file_name."', '')
   ";
   $statement = $connect->prepare($query);
   $statement->execute();
  }
 }
}

function file_already_uploaded($file_name, $connect)
{
 
 $query = "SELECT * FROM tbl_image WHERE image_name = '".$file_name."'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $number_of_rows = $statement->rowCount();
 if($number_of_rows > 0)
 {
  return true;
 }
 else
 {
  return false;
 }
}

?>


edit.php



<?php
//edit.php
include('database_connection.php');

$query = "
SELECT * FROM tbl_image 
WHERE image_id = '".$_POST["image_id"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

foreach($result as $row)
{
 $file_array = explode(".", $row["image_name"]);
 $output['image_name'] = $file_array[0];
 $output['image_description'] = $row["image_description"];
}

echo json_encode($output);

?>


update.php



<?php
//update.php

include('database_connection.php');

if(isset($_POST["image_id"]))
{
 $old_name = get_old_image_name($connect, $_POST["image_id"]);
 $file_array = explode(".", $old_name);
 $file_extension = end($file_array);
 $new_name = $_POST["image_name"] . '.' . $file_extension;
 $query = '';
 if($old_name != $new_name)
 {
  $old_path = 'files/' . $old_name;
  $new_path = 'files/' . $new_name;
  if(rename($old_path, $new_path))
  { 
   $query = "
   UPDATE tbl_image 
   SET image_name = '".$new_name."', image_description = '".$_POST["image_description"]."' 
   WHERE image_id = '".$_POST["image_id"]."'
   ";
  }
 }
 else
 {
  $query = "
   UPDATE tbl_image 
   SET image_description = '".$_POST["image_description"]."' 
   WHERE image_id = '".$_POST["image_id"]."'
   ";
 }
 
 $statement = $connect->prepare($query);
 $statement->execute();
}
function get_old_image_name($connect, $image_id)
{
 $query = "
 SELECT image_name FROM tbl_image WHERE image_id = '".$image_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row["image_name"];
 }
}

?>


delete.php



<?php
//delete.php

include('database_connection.php');

if(isset($_POST["image_id"]))
{
 $file_path = 'files/' . $_POST["image_name"];
 if(unlink($file_path))
 {
  $query = "DELETE FROM tbl_image WHERE image_id = '".$_POST["image_id"]."'";
  $statement = $connect->prepare($query);
  $statement->execute();
 }
}

?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_image`
--

CREATE TABLE IF NOT EXISTS `tbl_image` (
  `image_id` int(11) NOT NULL,
  `image_name` varchar(250) NOT NULL,
  `image_description` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_image`
--
ALTER TABLE `tbl_image`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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

49 comments:

  1. I need the images to disappear as soon as I register the product. When I go to register another product I need the upload area to be clean.

    ReplyDelete
  2. Please mention to create a folder "files" for the image to be stored.

    ReplyDelete
  3. i need to add image_description also while uploading multiple images so kindly share the code and please do need full i already tried by adding input field for image_description beside browse button but i ca't able to add the same in database ..

    ReplyDelete
  4. Hello there.
    I thank you for the work you share. I have a question. I've added a new field called "detail" to the edit form. I integrated CKEDITOR and KCFINDER into this field. edit button but CKeditor does not appear and I do not save it in the database when I save it. What do I have to do for that? If you help me, please.

    ReplyDelete
  5. Tekrar nerhaba
    lütfen yardım edin. çok uğraştım fakat yapamadım. CKEDİTOR entegre edemedim.
    teşekkürler

    ReplyDelete
  6. Thank you Sir! I am very happy to do this project. Very useful for me. But edit button didn't work. I don't know why? Delete is ok but not remove table. How to write in description column? There is some problem for me to correct but really I appreciate you.Thanks once more.

    ReplyDelete
  7. Can you show an example using ajax and OOP? Also, make it to where the mysql is recording under a certain ID? Example: Property Pictures for Property = 10T

    ReplyDelete
  8. Hi.
    I try this code, but I don't upload new images, beacuse script show is uploaded but I don't have new image on site and in folder and in base sql.
    Please help me.

    ReplyDelete
  9. you have to create folder "files" to store files

    ReplyDelete
  10. I love this , but I can't get but one image to upload at a time, and sometimes when I try to upload a single image, it overwrites the existing image. Is there something I am missing? Thank you this beautifully written.

    ReplyDelete
  11. u hafta create folder to store IMG & there is no insert

    ReplyDelete
  12. ::)) its working good.... u all plz make a folder in directory "files".

    ReplyDelete
  13. I couldn't update images to the folder

    ReplyDelete
  14. one thing you have to notice while run the above code

    create a "files" folder into your location it will run properly

    ReplyDelete
  15. thank for this tutorial and source code ...

    ReplyDelete
  16. I love the way the lecturer teaches and provide proper source code with the content.

    ReplyDelete
  17. You are a true king in backend coding and teaching. Thanks a million for this tutorial!

    ReplyDelete
  18. I created a files folder in my location. And yet it still don't upload images. I hope that somebody here might help thanks.

    ReplyDelete
  19. how to increase bytes ?? pls help me

    ReplyDelete
  20. Nice tutorial but edit button is not working and image description is not being uploaded. Can you please help?. Thanks

    ReplyDelete
  21. thanks.image is uploaded. and i also have to pass the description about the image.how can i do it?pls help.

    ReplyDelete
  22. thank you fine sire for this

    ReplyDelete
  23. Thank you so much ... i love your codes and lectures

    ReplyDelete
  24. how if we multi delete image using checkbox sir

    ReplyDelete
  25. It actually says file uploaded but nothing shows and when you try to upload more than two images it says file 0 file Size is very big

    ReplyDelete
  26. It's adding the images to the folder but not displaying on the page, wat could be the issue here

    ReplyDelete
  27. Nice work, you are the best!

    ReplyDelete
  28. There is two kind of of error in upload.php on line 4
    one is notice error another is warning error
    i want to modify this code for project purpose please help me
    because with this error this code is not working

    ReplyDelete
  29. hello is there a way to show the immage name without the extension

    ReplyDelete
  30. Thank you very much. It's working properly. create a folder named "files" in the root directory and it will be working properly.

    ReplyDelete
  31. How to resize before unloading

    ReplyDelete
  32. thanks for this codes, very useful, love it

    ReplyDelete
  33. superb this.. Thanks you so much !!

    ReplyDelete
  34. Is there a way on how can i add a category upon inserting the data? because trying to insert a POST value on the database doesnt work at all.

    https://stackoverflow.com/questions/59701545/post-value-not-being-retrieved-ajax-jquery

    ReplyDelete
  35. Hi, I have everything working up until edit. Loads and displays but I can't get modal to work and I'm confused on what to replace in script. I have a table wof with wofid, wofname and woftitle. Where do I use these in the edit part of the script to replace image_id, image_name and image_description. Please Help, Paul

    ReplyDelete
  36. How to code

    How to add text on image and than image download .please reply

    ReplyDelete
  37. Great job. Works well. I do have problem. I'm trying to add another input field. Not working. Please help. Thank you

    ReplyDelete
  38. Thank you. It was really helpful. Keep it up.

    ReplyDelete
  39. Worked first time! Thanks.

    If you refresh index.php, the name of the last file uploaded remains next to the 'Browse' button. How can you have this area refresh and remove this?

    ReplyDelete
  40. Am not getting response from backend. What do i do?

    ReplyDelete
  41. Nice, very helpful
    You need to create a Folder Name "files" in you Code Folder

    ReplyDelete
  42. How do i add a "Search block on top of this table" to filter records?

    ReplyDelete