Skip to main content

Image Upload using AJAX in PHP/MySQLi

This tutorial will teach you how to upload images using AJAX in PHP/MySQLi.

Creating our Database

First step is to create our database. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as upload. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `photo` (
  2. `photoid` INT(11) NOT NULL AUTO_INCREMENT,
  3. `location` VARCHAR(150) NOT NULL,
  4. PRIMARY KEY(`photoid`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ajaxupload

Creating our Connection

Next, we create our connection to our database. This will serve as the bridge between our forms and database. We name this as conn.php.
  1. <?php
  2.  
  3. $conn = mysqli_connect("localhost","root","","upload");
  4. if (!$conn) {
  5. die("Connection failed: " . mysqli_connect_error());
  6. }
  7.  
  8. ?>

index.php

We create our upload form and we show the images uploaded in this page.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Image Upload using AJAX in PHP/MySQLi</title>
  5. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  6. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  7. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  8. </head>
  9. <body>
  10. <div class="container">
  11. <div style="height:50px;"></div>
  12. <div class="row">
  13. <div class="well" style="width:80%; padding:auto; margin:auto">
  14. <form>
  15. <h2 align="center" style="color:blue">Image Upload using AJAX in PHP/MySQLi</h2>
  16. <label>Select Image:</label>
  17. <input type="file" name="file" id="file"><br>
  18. <button type="button" id="upload_button" class="btn btn-primary">Upload</button>
  19. </form>
  20. </div>
  21. </div>
  22. <div style="height:50px;"></div>
  23. <div style="width:80%; padding:auto; margin:auto;">
  24. <div id="image_area"></div>
  25. </div>
  26. </div>
  27. </body>
  28. <script src="custom.js"></script>
  29. </html>

fetch_photo.php

This is our code in fetching uploaded photos from our database.
  1. <?php
  2. include('conn.php');
  3. if(isset($_POST['fetch'])){
  4. $inc=4;
  5. $query=mysqli_query($conn,"select * from photo");
  6. while($row=mysqli_fetch_array($query)){
  7. $inc = ($inc == 4) ? 1 : $inc+1;
  8. if($inc == 1) echo '<div class="row">';
  9. ?>
  10. <div class="col-lg-3"><img src="<?php echo $row['location']?>" style="height:200px; width:100%;"></div>
  11.  
  12. <?php
  13. if($inc == 4) echo '</div>';
  14. }
  15. if($inc == 1) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div><div class="col-lg-3"></div></div>';
  16. if($inc == 2) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div></div>';
  17. if($inc == 3) echo '<div class="col-lg-3"></div></div>';
  18. }
  19.  
  20. ?>

upload.php

This is our code in uploading images into our database.
  1. <?php
  2. include('conn.php');
  3. if($_FILES["file"]["name"] != '')
  4. {
  5. $newFilename = time() . "_" . $_FILES["file"]["name"];
  6. $location = 'upload/' . $newFilename;
  7. move_uploaded_file($_FILES["file"]["tmp_name"], $location);
  8.  
  9. mysqli_query($conn,"insert into photo (location) values ('$location')");
  10. }
  11. ?>

custom.js

Lastly, this contains our jQuery and AJAX code in uploading and fetching our images.
  1. $(document).ready(function(){
  2.  
  3. showPhoto();
  4.  
  5. $(document).on('click', '#upload_button', function(){
  6. var name = document.getElementById("file").files[0].name;
  7. var form_data = new FormData();
  8. var ext = name.split('.').pop().toLowerCase();
  9. if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1){
  10. alert("Invalid Image File");
  11. }
  12. var oFReader = new FileReader();
  13. oFReader.readAsDataURL(document.getElementById("file").files[0]);
  14. var f = document.getElementById("file").files[0];
  15. var fsize = f.size||f.fileSize;
  16. if(fsize > 2000000){
  17. alert("Image File Size is very big");
  18. }
  19. else{
  20. form_data.append("file", document.getElementById('file').files[0]);
  21. $.ajax({
  22. url:"upload.php",
  23. method:"POST",
  24. data: form_data,
  25. contentType: false,
  26. cache: false,
  27. processData: false,
  28. success:function(){
  29. showPhoto();
  30. }
  31. });
  32. }
  33. });
  34. });
  35.  
  36. function showPhoto(){
  37. $.ajax({
  38. url:"fetch_photo.php",
  39. method:"POST",
  40. data:{
  41. fetch:1,
  42. },
  43. success:function(data){
  44. $('#image_area').html(data);
  45. }
  46. });
  47. }
That ends this tutorial. If you have any comments or questions, feel free to comment below or message me. Happy Coding :)

Add new comment