Managing and manipulating media files, especially images, is common in web development. When storing images, developers typically have two options: storing them directly in a database or web server. This tutorial will guide you through uploading images to a MySQL database using PHP.
PHP Image Upload to MySQL Database Demo
Step-by-Step Guide to Upload Images to MySQL Database Using PHP
Database Table Creation
Before beginning with the PHP code, we must create the MySQL table where the image will be stored. The SQL script for creating the table is as follows:
CREATE TABLE `tbl_media` (
`MediaID` int(11) NOT NULL AUTO_INCREMENT,
`Media` longblob NOT NULL,
PRIMARY KEY (`MediaID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
The data type of the media field is LONGBLOB. This type of BLOB (Binary Large OBject) is used in MySQL to store binary data like images, audio files, video files, etc.
Step 1: Set Up Database Connection
Make sure you have a config.php
file to connect to your MySQL database. This file should include connection details such as hostname, database name, username, and password.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "w3demo";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
Step 2: Check for Successful Image Upload
It is best if you first verify that the image upload was successful. If the image upload is successful, $_FILES["media"]["error"]
will be set to 0
.
if (isset($_FILES["Media"]) && $_FILES["Media"]["error"] == 0) {
// Image upload successful.
}
Step 3: Get Uploaded Image Content
Use the file_get_contents
function to get the content of the uploaded image.
$uploadedImageContent = file_get_contents($_FILES['Media']['tmp_name']);
Step 4: Prepare the SQL Query
Next, using the mysqli_prepare
function, create a SQL query to insert the image content into the tbl_media
table.
$insertImageStmt = mysqli_prepare($conn, "INSERT INTO tbl_media(Media) VALUES(?)");
Step 5: Bind Image Content to SQL Query
Bind the uploaded image content to the SQL query using the mysqli_stmt_bind_param
function.
mysqli_stmt_bind_param($insertImageStmt, 's', $uploadedImageContent);
Step 6: Execute SQL Query
Use mysqli_stmt_execute
function to execute the SQL query and insert the image into the database.
if (mysqli_stmt_execute($insertImageStmt)) {
// Upload successful
$message = "Upload successful.";
} else {
// Upload failed
$message = "Upload failed: " . mysqli_stmt_error($insertImageStmt);
}
Step 7: Display the Uploaded Image
Finally, you can retrieve and display the most recent image uploaded to the database. The image can be displayed by printing an HTML img tag with the base64 encoded image data.
echo '<img src="data:image/jpeg;base64,' . base64_encode($imageRow['Media']) . '" alt="Uploaded Image">';
That is all! Using PHP, You successfully uploaded and displayed an image from the MySQL database. This strategy can be useful in various situations, such as when uploading user profile images, product image galleries, or any other images that need to be stored directly in the database.