Web20 University

Live Image Upload with jQuery, PHP and MySQL

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

In this tutorial, we’ll create a dynamic image upload system that allows users to upload multiple images simultaneously without page refresh. We’ll use jQuery for the front-end interaction, PHP for server-side processing, and MySQL for storing image metadata.

Setting Up the Database

First, let’s create a MySQL table to store our image information:

CREATE TABLE images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    original_name VARCHAR(255) NOT NULL,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

PHP Template Setup

Create an index.php file with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Image Upload</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        #preview { margin-top: 20px; }
        #preview img { max-width: 200px; margin: 10px; }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1>Live Image Upload</h1>
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="form-group">
                <label for="images">Select Images:</label>
                <input type="file" class="form-control-file" id="images" name="images[]" multiple accept="image/*">
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>
        <div id="preview"></div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

Adding jQuery Functionality

Create a script.js file with the following content:

$(function() {
    $('#uploadForm').on('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                var data = JSON.parse(response);
                if(data.success) {
                    $('#preview').html('');
                    data.images.forEach(function(image) {
                        $('#preview').append('<img src="uploads/' + image.filename + '" alt="' + image.original_name + '">');
                    });
                } else {
                    alert('Upload failed: ' + data.message);
                }
            },
            error: function() {
                alert('An error occurred during upload.');
            }
        });
    });

    $('#images').on('change', function() {
        $('#preview').html('');
        var files = this.files;
        for(var i = 0; i < files.length; i++) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#preview').append('<img src="' + e.target.result + '">');
            }
            reader.readAsDataURL(files[i]);
        }
    });
});

Creating the Upload Process

Create an upload.php file to handle the server-side upload process:

<?php
$db = new mysqli('localhost', 'username', 'password', 'database_name');

if ($db->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed']));
}

$uploadDir = 'uploads/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$uploadedImages = [];

if(isset($_FILES['images'])) {
    foreach($_FILES['images']['tmp_name'] as $key => $tmp_name) {
        $file_name = $_FILES['images']['name'][$key];
        $file_size = $_FILES['images']['size'][$key];
        $file_tmp = $_FILES['images']['tmp_name'][$key];
        $file_type = $_FILES['images']['type'][$key];
        
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $extensions = ["jpeg","jpg","png","gif"];
        
        if(in_array($file_ext, $extensions)) {
            $upload_name = uniqid() . '.' . $file_ext;
            $upload_path = $uploadDir . $upload_name;
            
            if(move_uploaded_file($file_tmp, $upload_path)) {
                $stmt = $db->prepare("INSERT INTO images (filename, original_name) VALUES (?, ?)");
                $stmt->bind_param("ss", $upload_name, $file_name);
                $stmt->execute();
                
                $uploadedImages[] = ['filename' => $upload_name, 'original_name' => $file_name];
            }
        }
    }
    
    echo json_encode(['success' => true, 'images' => $uploadedImages]);
} else {
    echo json_encode(['success' => false, 'message' => 'No files were uploaded.']);
}

$db->close();

Conclusion

In this tutorial, we’ve created a live image upload system using jQuery, PHP, and MySQL. This system allows users to:

  1. Select multiple images for upload
  2. See a preview of selected images before upload
  3. Upload images without page refresh
  4. View uploaded images immediately after successful upload

Key points to remember:

  1. Always validate and sanitize user inputs on the server-side
  2. Use prepared statements to prevent SQL injection
  3. Implement proper error handling and user feedback
  4. Consider implementing file size limits and additional security measures

By leveraging the power of jQuery for asynchronous uploads and PHP for server-side processing, we’ve created a smooth and efficient image upload experience.

Get up to 65% Off Hosting with FREE SSL & FREE Domains!