In this post we will how to upload images in database using the jQuery AJAX function. It’s easy to learn on the site. In the previous post, we saw an example of uploading a PHP image jQuery AJAX in a folder not inserted data in database. In this example, I added code to upload in database PHP images using AJAX without reloading the page.
I use jQuery AJAX to implement image uploads. There is a form with file input fields and a upload buttons. When a form with the selected image file is sent, the AJAX script is run. In this code, a PHP upload request is sent with the uploaded image. The PHP code moves the uploaded image to the uploads folder and insert the image name in database and returns the HTML image to display the preview in AJAX response.
First of all, you need to understand that uploading users to your server can be a major security risk if you don’t validate correctly. So the most important part to consider is validation.
Create a Database in MySQL
The first step in this tutorial is the creation of a MySQL database. you can create tables by running SQL queries. Create a table ‘files’ in database using the following SQL query.
This will create a new table ‘files’ in the database. I will use this table to insert file.
-- -- Database: `registration` -- -------------------------------------------------------- -- Table structure for table `files` -- CREATE TABLE `files` ( `id` int(50) NOT NULL PRIMARY KEY AUTO_INCREAMENT, `image` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Create MySql Connection in PHP
For importing and exporting database in MySql will make a separate file ‘dbConfig.php’. Add the following code and replace the database credentials with yours. You can find your db credentials in Application Access details:
dbConfig.php
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "registration"; // Create database connection $con = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create the HTML Form
index.php
<!Doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Upload Image in Database & Display Using jQuery AJAX PHP and MySQL</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body style="margin-top:50px;background:#f2f2f2"> <div class="container"> <h2 style="text-align:center;">Upload Image in Database & Display Using jQuery AJAX PHP and MySQL</h2> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4" style="margin-top:20px;margin-bottom:20px;"> <span class="ajax-message"></span> <form id="submitForm"> <div class="form-group"> <label for="file">Select File</label> <input type="file" class="form-control" name="file" id="image" required=""> </div> <div class="form-group"> <button type="submit" class="btn btn-success btn btn-block">Upload</button> </div> </form> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="card col-md-4" id="preview" style="display: none;"> <div class="card-body" id="imageView"> </div> </div> </div> </div> </body> </html>
Uploading the image with jQuery AJAX
<!---jQuery ajax file upload ---> <script type="text/javascript"> $(document).ready(function(){ $("#submitForm").on("submit", function(e){ e.preventDefault(); var formData = new FormData(this); $.ajax({ url : "upload.php", type : "POST", cache:false, data :formData, contentType : false, // you can also use multipart/form-data replace of false processData: false, success:function(response){ $("#preview").show(); $("#imageView").html(response); $("#image").val(''); data = JSON.parse(response); if (data.error == '1') { $("#preview").hide(); } else if(data.error =='0'){ $('.ajax-message').replaceWith('<div class="alert alert-danger alert-dismissible" role="alert">' + data.message + ' <button type="button" class="close" data-dismiss="alert">×</button></div>'); $("#preview").hide(); } } }); }); }); </script>
Create PHP code for uploading image in database
upload.php
<?php // Include database connectivity include_once('dbConfig.php'); // upload file using move_uploaded_file function in php if (!empty($_FILES['file']['name'])) { $fileName = $_FILES['file']['name']; $fileExt = explode('.', $fileName); $fileActExt = strtolower(end($fileExt)); $allowImg = array('png','jpeg','jpg'); $fileNew = rand() . "." . $fileActExt; // rand function create the rand number $filePath = 'uploads/'.$fileNew; if (in_array($fileActExt, $allowImg)) { if ($_FILES['file']['size'] > 0 && $_FILES['file']['error']==0) { $query = "INSERT INTO files(image) VALUES('$fileNew')"; if (mysqli_query($con, $query)) { move_uploaded_file($_FILES['file']['tmp_name'], $filePath); echo '<img src="'.$filePath.'" style="width:320px; height:300px;"/>'; }else{ echo json_encode(array('error'=>'0', 'message'=>'File is not uploaded try again')); } }else{ echo json_encode(array('error'=>'0', 'message'=>'Unable to upload physical file')); } }else{ echo json_encode(array('error'=>'0', 'message'=>'Only PNG, JPEG, JPG image allow')); } } ?>
Output

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.😊