Php

PHP Image Upload Using jQuery and MySQL

This is another image upload tutorial using PHP, jQuery and MySQL. I have already shared the tutorial Image Upload,Crop and Resize Using PHP, jQuery and Ajax.

This tutorial is uploading images to a folder and stores image names into the database table. I am not cropping or resizing images, it’s a simple PHP image upload tutorial.

You can also use the modal box for image upload with help of Image Crop Functionality In Model Box Using PHP tutorial.

I am using jQuery to submit an image and process server-side data so this tutorial helps to ajax based image upload using PHP and jQuery.

  • jQuery Library: Base library to support other jquery plugins.
  • Boostrap 3: Used to create the awesome HTML layout
  • Index.php: This is the main file of this project that will contain HTML code with file upload FORM and jquery code to submit the form.
  • connection.php: Use to create a database connection with MySQL.
  • upload.php: This file contains PHP code to upload an image into a folder and save the image name into the database table.

Simple PHP Image Upload Using AJAX and MySQL

I will create d:/image_upload_code folder and create index.php file into this folder. We will create test database and users_image table, We will create a table using the below SQL.

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 add the below code into this file to create a database connection with MySQL.

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

Related Post

Step 2: We will add bootstrap and jQuery library files into the head section of index.php file.

<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 an HTML form into index.php file.

Added upload.php file into the action of a form element. We will add jQuery code to submit form ajax manner using jQuery.

<form id="image_upload_form" action="upload.php" autocomplete="off" enctype="multipart/form-data" method="post">
 <div class="alert alert-danger hide">&nbsp;</div>
 <div class="alert alert-success hide">&nbsp;</div>
 <div class="col-md-6">
 <div class="form-group"><label>Upload Image</label>
 <p>&nbsp;</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 the form into the 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 the server side when the user will click submit button.

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 create an upload.php file and add the below code.

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

View Comments

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories