Uploading and Downloading Images to from MySQL database-php

Last modified: April 06, 2022

You need to be able to run PHP Script on your computer and have MySQL database running. If you do not have them, you can view this tutorial.

Run the following SQL script on phpMyAdmin or MySQL Workbench to create a database and table.

if you do not have MySQL Workbennch, you can download if from

1. SQL
create DATABASE demo; CREATE TABLE `Product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `file` BLOB NOT NULL, `filename` varchar(50) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2. Jquery

For easier writing JavaScript, we use JQuery library, hence we import it on head section

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
3. Upload HTML form

we need enctype="multipart/form-data" if we want to upload file

<form action="" method="post" enctype="multipart/form-data"> <input type="file" id="image" name="image"> <input type="submit" name = 'submitImage'> </form>
4. dbconfig.php

Create a PHP called dbconfig.php and save it with following content.4

<?php $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "demo"; $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
5. Upload PHP Code
<?php include_once 'include/dbconfig.php'; // If form is submitted if(isset($_POST['submitImage'])){ $data = file_get_contents($_FILES["image"]["tmp_name"]); //get the fike path $filename=$_FILES['image']['name']; //get filename // Insert form data in the database $stmt = $db->prepare("INSERT INTO product (file, filename) VALUES (?, ?)"); $stmt->bind_param("ss", $data, $filename); $insert= $stmt->execute(); $stmt->close(); } ?>
6. Display the table

convert Blob data into JPG file

<?php $sql = "SELECT * FROM product"; $result = $db->query($sql); echo "<table>"; echo "<thead>"; echo " <tr>"; echo " <th>"; echo " <b>File Name</b>"; echo " <b>Image</b>"; echo " </th>"; echo " </tr>"; echo " </thead>"; echo " <tbody>"; if ($result){ while($row = mysqli_fetch_assoc($result)) { echo " <tr>"; echo " <td>".$row['filename']."</td>"; echo '<td><img src="data:image/jpeg;base64,'.base64_encode($row['file']).'"/></td>'; echo " </tr>"; } } echo" </tbody>"; echo"</table>"; ?>
7 Test

test