Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Upload Image into Database and Display it using PHP
In modern web applications, it is common to store images in databases for various reasons, such as security, easy management, and scalability. PHP provides an easy way to upload images to databases and display them on web pages.
In this article, we will learn how to upload images into database and display them using PHP. We will implement the following functionality
HTML form to upload an image
Upload an image to the server using PHP
Store file data in the database using PHP and MySQL
Retrieve images from the database and display on the web page
Prerequisites: Make sure you have a web server with PHP and MySQL installed (XAMPP, WAMP, or similar). You'll also need access to phpMyAdmin or another database management tool.
Step 1: Create a Database and Table
First, create a database table to store the image data. The table must have a column of type "LONGBLOB" (Binary Large Object) to store large binary data like images ?
CREATE TABLE images ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, type VARCHAR(100) NOT NULL, data LONGBLOB NOT NULL );
Step 2: Create an HTML Form to Upload an Image
Create an HTML form that allows users to select and upload an image. The form must have an input field of type "file" and use enctype="multipart/form-data" ?
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h2>Upload Image</h2>
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
Step 3: Processing the Uploaded Image
Create a PHP script that processes the uploaded image and stores it in the database. This script validates the upload and inserts the binary data ?
<?php
// upload.php
if(isset($_POST['submit']) && isset($_FILES['image'])) {
$image = $_FILES['image'];
// Check for upload errors
if($image['error'] == 0) {
$name = $image['name'];
$type = $image['type'];
$data = file_get_contents($image['tmp_name']);
// Validate file type
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
if(in_array($type, $allowed_types)) {
try {
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=tutorialspoint', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Insert the image data into the database
$stmt = $pdo->prepare("INSERT INTO images (name, type, data) VALUES (?, ?, ?)");
$stmt->execute([$name, $type, $data]);
echo "Image uploaded successfully! ID: " . $pdo->lastInsertId();
} catch(PDOException $e) {
echo "Database error: " . $e->getMessage();
}
} else {
echo "Invalid file type. Only JPEG, PNG, and GIF are allowed.";
}
} else {
echo "Upload error occurred.";
}
}
?>
Step 4: Displaying the Image from Database
Create a PHP script that retrieves the image data from the database and outputs it as binary data with the appropriate MIME type ?
<?php
// display.php
if(isset($_GET['id'])) {
$id = (int)$_GET['id'];
try {
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=tutorialspoint', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Retrieve the image data from the database
$stmt = $pdo->prepare("SELECT name, type, data FROM images WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row) {
// Set the content type header
header("Content-Type: " . $row['type']);
header("Content-Disposition: inline; filename="" . $row['name'] . """);
// Output the image data
echo $row['data'];
} else {
echo "Image not found.";
}
} catch(PDOException $e) {
echo "Database error: " . $e->getMessage();
}
} else {
echo "No image ID specified.";
}
?>
Step 5: Displaying Images on a Web Page
Create a web page that displays all uploaded images using HTML img tags pointing to the display script ?
<?php
// gallery.php
try {
$pdo = new PDO('mysql:host=localhost;dbname=tutorialspoint', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT id, name FROM images ORDER BY id DESC");
$images = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo "Database error: " . $e->getMessage();
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Gallery</title>
<style>
.gallery { display: flex; flex-wrap: wrap; gap: 10px; }
.gallery img { max-width: 200px; max-height: 200px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h2>Image Gallery</h2>
<div class="gallery">
<?php foreach($images as $image): ?>
<div>
<img src="display.php?id=<?= $image['id'] ?>" alt="<?= htmlspecialchars($image['name']) ?>" />
<p><?= htmlspecialchars($image['name']) ?></p>
</div>
<?php endforeach; ?>
</div>
</body>
</html>
Key Points
Use
LONGBLOBdata type for storing binary image dataAlways validate file types and handle upload errors
Set proper content-type headers when outputting images
Use prepared statements to prevent SQL injection
Conclusion
Uploading images to a database using PHP involves creating a proper database structure, handling file uploads securely, and displaying images through separate scripts. This approach provides centralized storage and easy management of images in web applications.
