Upload Multiple Image in Database & Retrieve using jquery AJAX in PHP MYSQL


Upload Multiple Image in Database & Retrieve using jquery AJAX in PHP MYSQL

In this post we will learn How to upload multiple images in database & retrieve using jQuery AJAX in PHP MYSQL. Files uploading is very important feature in web development. There are many ways to save images. One that we can use to upload images to the server and store the image names in the MySQL database is using PHP. Alternatively, we can store images directly in MySQL database tables, also with PHP. There are many posts that we post when we upload one image or several images to the server and store image details in the database using PHP. However, in this post we have covered an advance topic about inserting multiple images into a MySQL database using PHP with jQuery Ajax.

In one of our previous posts, we explained step by step how to upload multiple images using jquery AJAX in PHP MYSQL But in this post, we will only be using a PHP script to insert images into a MySQL database and then fetch the images from the MySQL database and display the web page using PHP. However, here we have a form with the option to select multiple images at once and use jQuery Ajax to send these images to PHP. The PHP script insert the image unique name into the MySQL database one by one. Now that we have added some images to the MySQL database, we now want to fetch the images from the MySQL database and display them on a web page. To do this, we also use the jQuery and Ajax functions, which send a request to PHP, in a PHP script that fetch data from a MySQL table, converts this data to HTML format and sends it back to the Ajax request. Now let’s cover sources for uploading multiple images to database using PHP Ajax.

Output

Upload Multiple Image in Database & Retrieve using jquery AJAX in PHP MYSQL

See also

MySQL Database Table

--
-- Database: `registration`

-- Table structure for table `table_images`
--

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

Database Connection 

dbConnection.php
<?php

// Database configuration

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

// 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 for Upload Multiple Files 

index.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload Multiple Image in Database & Retrieve using jquery AJAX in 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>Upload Multiple Image in Database & Retrieve using jquery AJAX in 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-success btn-block">Upload File</button>
</div>
</form>
</div>
</div>
<!-- gallery view of uploaded images -->
<div id="gallery"></div>
</div>

</body>
</html>

jQuery AJAX Code Upload Multiple Images

<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();
    }
     });
    });
});
</script>

Upload Multiple Images 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','');

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

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

    if ($_FILES['multipleFile']['size'][$name] > 0 && $_FILES['multipleFile']['error'][$name]== 0) {

$fileTmp = $_FILES['multipleFile']['tmp_name'][$name];

$newFile = rand(). '.'. $fileExnt[1];

$target_dir = 'uploads/'.$newFile;

if (move_uploaded_file($fileTmp, $target_dir)) {
    $query = "INSERT INTO table_images (images) VALUES('$newFile')";
    mysqli_query($con, $query);
}
    }
}
    }
}

?>

jQuery AJAX Code Fetch Multiple Images

<script type="text/javascript">
$(document).ready(function(){
// Fetch Data from Database
function fetchData(){
$.ajax({
url : "fetch_data.php",
type : "POST",
cache: false,
success:function(data){
$("#gallery").html(data);
}
});
}
fetchData();
});
</script>

Fetch Multiple Images with PHP Code

fetch_data.php
<?php

// Database connection

require_once('dbConnection.php');


$query = "SELECT * FROM table_images";

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

if (mysqli_num_rows($result) > 0) {

    while ($row = mysqli_fetch_assoc($result)) {
$images = 'uploads/'. $row['images'];
echo'<img src="'.$images.'" class="img-thumbnail" width="220px" height="220px" style="margin:10px;" />';
    }

}else{
    echo "<h3 style='text-align:center'>No Image found</h3>";
}

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


Leave a Reply