How to Upload Image into Database Using PHP

Introduction to Upload Image into Database

In today’s digital age, image uploading and display functionality is a common requirement for many web applications. Whether you’re building a social media platform, an e-commerce site, or a personal blog, the ability to handle images is often a fundamental feature. In this tutorial, we will guide you through the process of uploading images to a MySQL database using PHP and displaying them on a web page.

Creating a Database and Table

Step 1: Database Setup

The first step in our journey is setting up the MySQL database where we will store our image data. You can create a new database using a MySQL client or a tool like phpMyAdmin. For this tutorial, let’s call our database your_database_name.

CREATE DATABASE project_akhand;

Step 2: Creating the Table

Within the project_akhand database, we’ll create a table named images to store our image data. This table will have columns to hold the image name, image binary data, image type, and a timestamp indicating when the image was uploaded. Here’s the SQL code to create the table:

CREATE TABLE images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image_name VARCHAR(255) NOT NULL,
    image_data LONGBLOB NOT NULL,
    image_type VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

With our database and table set up, we can move on to the PHP code that handles image uploads and displays.

Step 3: Make database connection db.php:

<?php

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_db_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Uploading Images to the Database

PHP Script for Image Upload

We’ll start by creating a PHP script that allows users to upload images. Here’s a simplified version of the PHP code index.php:

<?php
include "db.php";

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {


    // File upload handling
    $file_name = $_FILES["image"]["name"];
    $file_tmp = $_FILES["image"]["tmp_name"];
    $file_type = $_FILES["image"]["type"];

    $image_data = file_get_contents($file_tmp); // Read the image file into binary data

    // SQL query to insert the image into the database
    $sql = "INSERT INTO images (image_name, image_data, image_type) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sss", $file_name, $image_data, $file_type);

    if ($stmt->execute()) {
        echo "Image uploaded successfully.";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>Image Upload</title>
    <!-- Include Bootstrap CSS via CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        /* Custom CSS styles */
        body {
            padding: 20px;
        }

        .container {
            max-width: 800px;

        }
        .card{
            display: flex;
            align-items: center;
        }
        h2 {
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2 class="text-center">Upload an Image | apsinghdev.in</h2>
        <div class="card p-4">
                    <form method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="image">Select an Image: </label>
                <input type="file" class="form-control-file" id="image" name="image" accept="image/*" required>
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
            <a href="show-image.php" class="btn btn-secondary">Show Images</a>
        </form>
        </div>

    </div>

    <!-- Include Bootstrap JS and jQuery via CDN (optional) -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>

</html>

This script handles image uploads and stores them in the images table.

Displaying Images from the Database

PHP Script for Image Display

To display the uploaded images, we’ll create another PHP script. Here’s a simplified version of the code show-image.php:

<?php
include "db.php";
$sql = "SELECT image_data, image_type FROM images";
$stmt = $conn->prepare($sql);
$stmt->execute();

$stmt->bind_result($imageData, $imageType);

while ($stmt->fetch()) {
    // Output image data length for debugging
    $imageSizeMB = strlen($imageData) / (1024 * 1024); // Convert from bytes to megabytes

    // Output image data size in MB
    echo "Image Size: " . number_format($imageSizeMB, 2) . " MB<br>";

    // Output the image MIME type for debugging
    echo "Image Type: $imageType<br>";

    // Output a 
    echo '<img src="data:image/png;base64,' . base64_encode($imageData) . '" style="max-width: 300px; max-height: 300px;">';

    // Add a separator between images (optional)
    echo '<hr>';
}

$stmt->close();
?>

This script retrieves image data from the database and displays them on a web page. It generates HTML code for each image, which includes a link to another PHP script (show-image.php) for displaying the image itself.

Conclusion

In this tutorial, we’ve covered the process of uploading and displaying images in a MySQL database using PHP. This functionality can be a valuable addition to various web applications, allowing users to interact with images seamlessly. You can further enhance this code by adding features like image resizing, user authentication, and image management.


Our Recommendation

Avatar of Akhand Pratap Singh

Akhand Pratap Singh

Greetings and a warm welcome to my website! I am Akhand Pratap Singh, a dedicated professional web developer and passionate blogger.

Related Post

Leave a Comment





Newsletter

Subscribe for latest updates

We don't spam.

Loading

Categories