Do you want to upload an image to the database? Most application services move the uploaded files to a directory and save their path to the database.
Earlier, we saw code for storing uploaded images to the database using MySQL BLOB fields. BLOB(Binary Large Data Object) is one of the MySql data types. It can have the file binary data. MySQL supports four types of BLOB datatype as follows.
View demo
For this example, we created one of the above BLOB fields in a MySQL database to see how to upload an image. Added to that, this code will fetch and BLOB data from the database and display the image to the browser.
Before running this example, create the required database structure on your server.
CREATE TABLE images ( id INT(11) AUTO_INCREMENT PRIMARY KEY, image LONGBLOB NOT NULL );
This is a usual file upload form with a file input. This field restricts the file type to choose only the images using the accept attribute.
On submitting this form, the upload.php
receives the posted file binary data on the server side.
<!DOCTYPE html>
<html>
<head>
<title>PHP - Upload image to database - Example</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="form.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="phppot-container">
<h1>Upload image to database:</h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
<div class="row">
<input type="file" name="image" accept="image/*">
<input type="submit" value="Upload">
</div>
</form>
<h2>Uploaded Image (Displayed from the database)</h2>
</div>
</body>
</html>
This PHP script gets the chosen file data with the $_FILES
array. This array contains the base name, temporary source path, type, and more details.
With these details, it performs the file upload to the database. The steps are as follows,
file_get_contents($_FILES["image"]["tmp_name"])
.<?php
// MySQL database connection settings
$servername = "localhost";
$username = "root";
$password = "admin123";
$dbname = "phppot_image_upload";
// Make connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection and throw error if not available
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if an image file was uploaded
if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {
$image = $_FILES['image']['tmp_name'];
$imgContent = file_get_contents($image);
// Insert image data into database as BLOB
$sql = "INSERT INTO images(image) VALUES(?)";
$statement = $conn->prepare($sql);
$statement->bind_param('s', $imgContent);
$current_id = $statement->execute() or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_connect_error());
if ($current_id) {
echo "Image uploaded successfully.";
} else {
echo "Image upload failed, please try again.";
}
} else {
echo "Please select an image file to upload.";
}
// Close the database connection
$conn->close();
This PHP code prepares a SELECT query to fetch the image BLOB. Using the image binary from the BLOB, it creates the data URL. It applies PHP base64 encoding on the image binary content.
This data URL is set as a source of an HTML image element below. This script shows the recently inserted image on the screen. We can also show an image gallery of all the BLOB images from the database.
<?php
// Retrieve the uploaded image from the database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phppot_image_upload";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT image FROM images ORDER BY id DESC LIMIT 1");
if ($result && $result->num_rows > 0) {
$row = $result->fetch_assoc();
$imageData = $row['image'];
echo '<img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" alt="Uploaded Image" style="max-width: 500px;">';
} else {
echo 'No image uploaded yet.';
}
$conn->close();
?>
Thanks for the knowledge
Welcome!
how would i make a gallery of all the pictures uploaded to the datbase?
Hi Kevin,
I have published a tutorial to display an image gallery https://phppot.com/php/php-responsive-image-gallery-using-css-media-queries/
You may have to combine these two to get what you need.