How to Upload Image into Database and Display it using PHP
Table of Contents
Introduction
This tutorial will guide you through the process of uploading images to a database and displaying them using PHP. This is a common functionality in web applications where users need to submit images or videos. We will be using the WAMP server for this demonstration.
Step 1: Set Up Your Environment
Before you start coding, ensure that you have the following:
- WAMP Server: Download and install WAMP Server from the official website. This will provide you with a local server environment.
- Database: Create a database to store your images.
How to Create a Database
- Open the WAMP server and launch phpMyAdmin by navigating to
http://localhost/phpmyadmin
. - Click on the "Databases" tab.
- Enter a name for your database and click "Create."
- Once the database is created, create a table for storing image data. You can name it
images
with the following fields:id
(INT, Primary Key, Auto Increment)image
(BLOB)description
(VARCHAR)
Step 2: Create the HTML Form
You need a form to allow users to upload images. Create an HTML file named upload.html
and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image" required>
<input type="text" name="description" placeholder="Image Description" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
Tips
- Ensure the
enctype
attribute is set tomultipart/form-data
to handle file uploads.
Step 3: Write the PHP Script
Create a PHP file named upload.php
to handle the form submission and image upload. Add the following code:
<?php
$servername = "localhost";
$username = "root"; // default username
$password = ""; // default password
$dbname = "your_database_name"; // replace with your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$description = $_POST['description'];
$image = $_FILES['image']['tmp_name'];
$imageContent = addslashes(file_get_contents($image));
$sql = "INSERT INTO images (image, description) VALUES ('$imageContent', '$description')";
if ($conn->query($sql) === TRUE) {
echo "Image uploaded successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
Key Points
- Connection: Replace
your_database_name
with the actual name of your database. - Error Handling: The script checks for connection errors and handles SQL execution errors.
Step 4: Display Uploaded Images
Create another PHP file named display.php
to retrieve and display the images from the database. Use the following code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<div>';
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" />';
echo '<p>' . $row['description'] . '</p>';
echo '</div>';
}
} else {
echo "No images found.";
}
$conn->close();
?>
Important Notes
- Use
base64_encode
to convert the image data into a format that can be displayed in an HTML image tag.
Conclusion
You have now set up a complete system for uploading images to a database and displaying them using PHP. Here are the main takeaways:
- Set up WAMP Server and create a database.
- Create an HTML form for uploading images.
- Write PHP scripts to handle file uploads and to display images.
- Test your application by uploading images and viewing them in your browser.
Next steps could include enhancing the application by adding features like image validation, user authentication, or using AJAX for a better user experience.