This is another image upload tutorial using php, jQuery and MySQL. I have already shared tutorial Image Upload,Crop and Resize Using PHP, jQuery and Ajax.This tutorial is uploading image to folder and store image name into database table.I am not cropping or resizing image, its a simple php image upload tutorial, You can also use modal box for image upload with help of Image Crop Functionality In Model Box Using PHP tutorial.
I am using jQuery to submit image and process server side data so that this tutorial help to ajax based image upload using php and jQuery.
- jQuery Library : Base library to support other jquery plugin
- Boostrap 3 : Used to create awesome HTML layout
- Index.php : This is the main file of this project that will contains HTML code with file upload FORM and jquery code to submit form.
- connection.php : Use to create database connection with MySQL.
- upload.php : This file contains php code to upload image into folder and save image name into database table.
Simple PHP Image Upload Using AJAX and MySQL
I will create d:/image_upload_code
folder and created index.php
file into this folder.We will create test
database and users_image
table, We will create table using below SQL,
1 2 3 4 5 6 7 8 9 10 | CREATE TABLE IF NOT EXISTS `users_image` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user` varchar(255) DEFAULT NULL, `pass` varchar(100) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `profile_photo` varchar(200) DEFAULT NULL, PRIMARY KEY (`uid`), UNIQUE KEY `username` (`user`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
The table users_image
will contain user details user, pass, email and profile_photo.
Step 1: We will create connection.php
file and added below code into this file to create database connection with MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php Class dbObj{ /* Database connection start */ var $servername = "localhost"; var $username = "root"; var $password = ""; var $dbname = "test1"; var $conn; function getConnstring() { $con = mysqli_connect($this--->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error()); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $this->conn = $con; } return $this->conn; } } ?> |
You can change dbname, servername, username and password variable value as per your database credentials.
Step 2: We will add bootstrap and jQuery library files into head section of index.php
file.
1 2 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> |
Step 3: We will create HTML form into index.php
file.
Added upload.php
file into action of form element.We will add jQuery code to submit form ajax manner using jQuery.
1 2 3 4 5 6 7 8 9 10 | <form id="image_upload_form" action="upload.php" autocomplete="off" enctype="multipart/form-data" method="post"> <div class="alert alert-danger hide"> </div> <div class="alert alert-success hide"> </div> <div class="col-md-6"> <div class="form-group"><label>Upload Image</label> <p> </p> <div class="input-group"><input id="input_image_text" class="form-control" readonly="readonly" type="text" /> <span class="input-group-btn"> <span class="btn btn-success btn-file"> Browse… <input id="photoimg" name="photoimg" type="file" /> </span> <button class="btn btn-warning" type="submit"> <i class="glyphicon glyphicon-upload"></i> upload </button> </span></div> </div> </div> </form> |
Step 4: We will add jQuery code to submit form into footer of index.php
.
I have added code to set filename into input text.I have also added submit form jquery code, to submit form data into server side when the user will click submit button.
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 | jQuery(document).ready(function(){ $('#photoimg').on('change', function() { var label = $(this).val().replace(/\\/g, '/').replace(/.*\//, ''), input = $('#input_image_text').val(label); $('.alert').addClass('hide'); $('.alert').removeClass('show'); }); var frm = $('#image_upload_form'); frm.submit(function (e) { e.preventDefault(); var formData = new FormData(); formData.append('photoimg', $('#photoimg')[0].files[0]); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: formData, dataType: "json", processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success: function (data) { console.log(data['error']); if(data.error == 1) { $('.alert-danger').removeClass('hide').addClass('show').html(data['msg']); } else { $('.alert-success').removeClass('hide').addClass('show').html('Uploaded'); console.log(data); } }, error: function (data) { console.log(data); $('.alert-danger').removeClass('hide').addClass('show').html(data); }, }); }); }); |
Step 5: We will created upload.php
file and added below code.
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 | <!--?php include_once("connection.php"); $db = new dbObj(); $connString = $db--------->getConnstring(); $path = "images/"; $valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; //print_R($_POST);die; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_file_formats)) { if($size<(1024*1024)) { $user_id = 1; $image_name = time().'_'.$user_id.".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$image_name)){ $sql = "UPDATE users_image SET image='".$image_name."' WHERE id=$user_id"; $result = mysqli_query($connString, $sql) or die("error to update image data"); echo json_encode(array('error'=>0, 'msg' => "Successfully! Uploaded image..")); } else echo json_encode(array('error'=>1, 'msg' => "Image Upload failed..!")); } else echo json_encode(array('error'=>1, 'msg' => "Image file size maximum 1 MB..!")); } else echo json_encode(array('error'=>1, 'msg' => "Invalid file format..!")); } else echo json_encode(array('error'=>1, 'msg' => "Please select image..!")); exit; } ?> |
You can download source code and see Demo from below link.