Ajax Multiple Image Upload with Edit Update Delete using PHP Mysql

Here you will not only learn how to upload multiple images or files without reload forms using Ajax JQuery using PHP, but also how to edit or update image information in databases and folders, as well as delete or update Delete images from folders and from a Database. We have covered many topics in this one topic so you can learn a lot from this single post. In one of our tutorials we discussed How to Upload Multiple Image in Database & Retrieve using jquery AJAX in PHP MYSQL. But here we are uploading some images with our event for submitting the form using Ajax JQuery as front end and back end of PHP and MySQL.

If multiple images are uploaded to the folder after we have uploaded the images, details such as image name will be shown in the table. All uploaded image data will be entered into a MySQL table. After uploading the image, we use the Ajax function to fetch the image details from the MySQL table and display the web page in tabular form with edit and delete buttons. Uploading some images and then inserting the uploaded image data into a MySQL table the process is done without updating the web page as we are using Ajax for these things with PHP and MySQL.

After successfully uploading the image with the data pasted into the MySQL table. Suppose we want to edit or update some details like image name  and then things we do with the bootstrap modal. When we hit the edit button certain image details are available with a popup bootstrap modal. Here we can change not only the name of the image in the MySQL table, but also the name of the image in the folder. Similarly, deleting or deleting not only removes data from the image from the MySQL table, but also deletes or deletes the image from the folder. Here this process takes place without updating the website because we are using Ajax JQuery with PHP MySQL. In short, in this post we are doing an insert update and deleting some images in PHP using MySQL.

output

Ajax Multiple Image Upload with Edit Update Delete using PHP Mysql

MySQL Database & Table

In the first step we need to create a database and tables, so here I have created a database of tables webscodex and images with identifiers and columns with names. You simply create a Users table as described in the SQL query.

--
-- Database: `webscodex`

-- Table structure for table `images`
--

CREATE TABLE `table_images` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREAMENT,
  `images` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Database Connection

dbConnection.php

<?php

	// Database configuration 

	$sernamename = "localhost";
	$username    = "root";
	$passoword   = "";
	$databasename= "webscodex";

	// Create database connection
	$con = mysqli_connect($sernamename, $username,$passoword,$databasename);

	// Check connection
	if ($con->connect_error) {
		die("Connection failed". $con->connect_error);
	}

?>

Create HTML Code using Bootstrap for Upload Multiple Files

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Ajax Multiple Image Upload with Edit Update Delete using PHP Mysql</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<div class="jumbotron text-center">
  <h2>Ajax Multiple Image Upload with Edit Update Delete using PHP Mysql</h2>
</div>

<div class="container">
  <div class="row">
  	<div class="col-md-3"></div>
      <div class="col-md-6">
        <div class="alert alert-success alert-dismissible" id="success" style="display: none;">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          File uploaded successfully
        </div>
      <form id="submitForm">
        <div class="form-group">
          <div class="custom-file mb-3">
            <input type="file" class="custom-file-input" name="multipleFile[]" id="multipleFile" required="" multiple>
            <label class="custom-file-label" for="multipleFile">Choose Multiple Images to Upload</label>
          </div>
        </div>
        <div class="form-group">
          <button type="submit" name="upload" class="btn btn-primary" style="float:right;">Upload</button><br>
        </div>  
      </form><br>
    </div>
  </div>
</div>

  <!-- view of uploaded images -->
  <div class="container" id="gallery"></div>

  <!--Edit Multiple image form -->
  <div class='modal' id='exampleModal'>
    <div class='modal-dialog'>
      <div class='modal-content'>
        <div class='modal-header'>
          <h4 class='modal-title'>Update Image</h4>
          <button type='button' class='close' data-dismiss='modal'>&times;</button>
        </div>
        <div id="editForm">

        </div>
      </div>    
    </div>
  </div>

</body>
</html>

jQuery AJAX Code for Upload Multiple Files View Edit Update and Delete

<script type="text/javascript">
$(document).ready(function(){
    $("#submitForm").on("submit", function(e){
    e.preventDefault();
    $.ajax({
      url  :"upload.php",
      type :"POST",
      cache:false,
      contentType : false, // you can also use multipart/form-data replace of false
      processData : false,
      data: new FormData(this),
      success:function(response){
        $("#success").show();
        $("#multipleFile").val("");
        fetchData();
      }
    });
});

  // Fetch Data from Database
  function fetchData(){
    $.ajax({
      url  : "fetch_data.php",
      type : "POST",
      cache: false,
      success:function(data){
        $("#gallery").html(data);
      }
    });
  }
  fetchData();

  // Edit Data from Database
  $(document).on("click",".btn-success", function(){
    var editId = $(this).data('id');
    $.ajax({
      url : "edit.php",
      type : "POST",
      cache: false,
      data : {editId:editId},
      success:function(data){
        $("#editForm").html(data);
      }
    });
  });

  // Delete Data from database

  $(document).on('click','.delete-btn', function(){
    var deleteId = $(this).data('id');
    if (confirm("Are you sure want to delete this image")) {
      $.ajax({
        url  : "delete.php",
        type : "POST",
        cache:false,
        data:{deleteId:deleteId},
        success:function(data){
          fetchData();
          alert("Image is deleted successfully");
        }
      });
    }
  });

  // Update Data from database
  $(document).on("submit", "#editForm", function(e){
  e.preventDefault();
  var formData = new FormData(this);
  $.ajax({
      url  : "update.php",
      type : "POST",
      cache: false,
      contentType : false, // you can also use multipart/form-data replace of false
      processData : false,
      data: formData,
      success:function(response){
        $("#exampleModal").modal('hide');
        alert("Image updated successfully");
        fetchData();
      }
    });
  });
});

</script>

Upload Multiple Files with PHP Code

upload.php

<?php
	
	// Database connection 
	
	require_once('dbConnection.php');

	// Upload multiple image in Database using PHP MYSQL

	if (!empty($_FILES['multipleFile']['name'])) {

	    $multiplefile = $_FILES['multipleFile']['name'];

	    foreach ($multiplefile as $name => $value) {
		
	    $allowImg = array('png','jpeg','jpg','gif');	

	    $fileExnt = explode('.', $multiplefile[$name]);

	    $fileTmp = $_FILES['multipleFile']['tmp_name'][$name];
					
	    $newFile = 	rand(). '.'. $fileExnt[1];

	    $target_dir = 'uploads/'.$newFile; 

	if (in_array($fileExnt[1], $allowImg)) {

	    if ($_FILES['multipleFile']['size'][$name] > 0 && $_FILES['multipleFile']['error'][$name]== 0) {
					
		if (move_uploaded_file($fileTmp, $target_dir)) {
		    $query  = "INSERT INTO table_images (images) VALUES('$newFile')";
		    mysqli_query($con, $query);
		}
	    }
	}
    }
}	
?>

Fetch and Display Multiple Files with PHP Code

fetch_data.php

<?php

	// Database connection 
	
	require_once('dbConnection.php');

	$query = "SELECT * FROM table_images ORDER BY id DESC";
	
	$result = mysqli_query($con, $query);
	
	$output = "";

	if (mysqli_num_rows($result) > 0) {
		$output .= "<table class='table table-striped'>";
		$output .= "<thead>
			        <tr>
			          <th>S.no</th>
			          <th>Image Name</th>
			          <th>Edit</th>
			          <th>Delete</th>
			        </tr>
			      </thead>";
		while ($row = mysqli_fetch_assoc($result)) {
		$images = 'uploads/'. $row['images'];
		$output .=  "<tr>
			          <td>".$row["id"]."</td>
			          <td><img src='".$images."' class='img-thumbnail' width='150px' height='150px' /></td>
			          <td><button type='button' class='btn btn-success btn-sm' data-toggle='modal' data-target='#exampleModal' data-id='".$row["id"]."'>Edit</button></td>
			          <td><button type='button' class='btn btn-danger btn-sm delete-btn' data-id='".$row["id"]."'>Delete</button></td>
			        </tr>";
		}
		$output .="</tbody>
    			</table>";
    	echo $output;
	}else{
		echo "<h3 style='text-align:center'>No Image found</h3>";
	}

?>

Edit Files with PHP Code

edit.php

<?php

	// Database connection 
	
	require_once('dbConnection.php');

	if (isset($_POST['editId'])) {
	    $editId = $_POST['editId'];
	}

	if (!empty($editId)) {
		
	    $query  = "SELECT * FROM table_images WHERE id = $editId";

	    $result = mysqli_query($con, $query);

	if (mysqli_num_rows($result) > 0) {
				
	    $output = "";
				
	    while($row = mysqli_fetch_assoc($result)) {

	    $image = 'uploads/'.$row['images'];
			
	    $output.="<form id='editForm'>
			<div class='modal-body' style='height: 200px;'>
		            <input type='hidden' name='image_id' id='image_id' value='".$row['id']."'/>
			      <div class='form-group'>
				 <div class='custom-file mb-3'>
				   <input type='file' class='custom-file-input' name='file_name' id='file_name'>
				   <label class='custom-file-label'>Choose Images to Upload</label>
				   <img src='".$image."' class='img-thumbnail' width='200px' height='200px'/>
				  </div>
			       </div>
			 </div>
			 <div class='modal-footer'>
			   <button type='button' class='btn btn-danger' data-dismiss='modal'>Close</button>
			   <button type='submit' class='btn btn-success'>Update</button>
			 </div>
		    </form>";
		}
	    echo $output;	
	}
}

?>

Update Files With PHP Code

update.php

<?php
	
	// Database connection 
	
	require_once('dbConnection.php');

	if (isset($_POST['image_id'])) {
		
	    $image_id = $_POST['image_id'];
	}
	
	if (!empty($_FILES['file_name']['name'])) {

	     $fileTmp = $_FILES['file_name']['tmp_name'];

	     $allowImg = array('png','jpeg','jpg','gif');

	     $fileExnt = explode('.', $_FILES['file_name']['name']);

	     $fileActExt   = strtolower(end($fileExnt));

	     $newFile = rand(). '.'. $fileActExt;

	     $destination = 'uploads/'.$newFile;

	     if (in_array($fileActExt, $allowImg)) {
	        if ($_FILES['file_name']['size'] > 0 && $_FILES['file_name']['error']==0) {

		    $query = "SELECT * FROM table_images WHERE id = '$image_id'";

		    $result = mysqli_query($con, $query);

		    $row = mysqli_fetch_assoc($result);

		    $filePath = 'uploads/'.$row['images'];
				
		    if (move_uploaded_file($fileTmp, $destination)) {
			$update = "UPDATE table_images SET images = '$newFile' WHERE id = '$image_id'";
			mysqli_query($con, $update);
			unlink($filePath);
		    }
		}
	     }
	}
		
?>

Delete Files With PHP Code

Delete.php

<?php
	
	// Database connection 
	
	require_once('dbConnection.php');

	if (isset($_POST['deleteId'])) {
		
	    $deleteId = $_POST['deleteId'];

	    $sql = "SELECT * FROM table_images WHERE id = $deleteId";

    	    $result = mysqli_query($con, $sql);

	    $row = mysqli_fetch_assoc($result);

	    $filePath = 'uploads/'.$row['images'];

	    $query = "DELETE FROM table_images WHERE id = $deleteId";

	if (mysqli_query($con, $query)) {
	     unlink($filePath);
	}
   }

?> 

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions or problems about this tutorial, please comment on the form below.😊

Ajax Multiple Image Upload with Edit Update Delete using PHP Mysql

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *