article

Thursday, March 24, 2022

Jquery Ajax Image Upload with PHP MySQLi

Jquery Ajax Image Upload with PHP MySQLi

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `tbluploadphoto` (
  `photoid` int(11) NOT NULL,
  `location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `tbluploadphoto`
  ADD PRIMARY KEY (`photoid`);


ALTER TABLE `tbluploadphoto`
  MODIFY `photoid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//index.php
<!DOCTYPE html>
<html>
<head>
    <title>Jquery Ajax Image Upload with PHP MySQLi</title>
</head>
<body>
<div class="container">
  <div class="row">
      <form>
        <h2 align="center" style="color:blue">Jquery Ajax Image Upload with PHP MySQLi</h2>
        <label>Select Image:</label>
        <input type="file" name="file" id="file"><br>
        <button type="button" id="upload_button" class="btn btn-primary">Upload</button>
      </form>
  </div>
  <div style="width:80%; padding:auto; margin:auto;">
      <div id="imagelist"></div>
  </div>
</div>
<script>
$(document).ready(function(){
 
  showPhoto();
 
  $(document).on('click', '#upload_button', function(){
       
    var name = document.getElementById("file").files[0].name;
    var form_data = new FormData();
    var ext = name.split('.').pop().toLowerCase();
    if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1){
      alert("Invalid Image File");
    }
     
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("file").files[0]);
    var f = document.getElementById("file").files[0];
    var fsize = f.size||f.fileSize;
     
    if(fsize > 2000000){
      alert("Image File Size is very big");
    }else{
        form_data.append("file", document.getElementById('file').files[0]);
        $.ajax({
          url:"upload.php",
          method:"POST",
          data: form_data,
          contentType: false,
          cache: false,
          processData: false,  
          success:function(){
            showPhoto();
          }
        });
    }
     
  });
});
 
function showPhoto(){
  $.ajax({
      url:"fetch_photo.php",
      method:"POST",
      data:{
        fetch:1,
      },
      success:function(data){
        $('#imagelist').html(data);
      }
    });
}
</script>
</body>
</html>
conn.php
1
2
3
4
5
6
7
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>
fetch_photo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//fetch_photo.php
<?php
    include('conn.php');
    if(isset($_POST['fetch'])){
        $inc=4;
        $query=mysqli_query($conn,"select * from tbluploadphoto");
        while($row=mysqli_fetch_array($query)){
        $inc = ($inc == 4) ? 1 : $inc+1;
        if($inc == 1) echo '<div class="row">'
            ?>
                <div class="col-lg-3"><img src="<?php echo $row['location']?>" style="height:200px; width:100%;"></div>
  
            <?php
        if($inc == 4) echo '</div>';
        }
        if($inc == 1) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div><div class="col-lg-3"></div></div>';
        if($inc == 2) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div></div>';
        if($inc == 3) echo '<div class="col-lg-3"></div></div>';
    }
?>
uppload.php
1
2
3
4
5
6
7
8
9
10
11
12
//uppload.php
<?php
include('conn.php');
if($_FILES["file"]["name"] != '')
{
    $newFilename = time() . "_" . $_FILES["file"]["name"];
    $location = 'upload/' . $newFilename
    move_uploaded_file($_FILES["file"]["tmp_name"], $location);
     
    mysqli_query($conn,"insert into tbluploadphoto (location) values ('$location')");
}
?>

Related Post