PHP Upload Image to Database with MySql

by Vincy. Last modified on July 2nd, 2023.

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

  1. TINYBLOB
  2. BLOB
  3. MEDIUMBLOB
  4. LONGBLOB

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.

Database script

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 );

php upload image to database output

HTML form with an image upload option

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>

Insert an image into the database using PHP and MySql

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,

  1. Validate file array is not empty.
  2. Retrieve the image file content using file_get_contents($_FILES[“image”][“tmp_name”]).
  3. Prepare the insert and bind the image binary data to the query parameters.
  4. Execute insert and get the database record id.
<?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();

Fetch image BLOB from the database and display to UI

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();
    ?>

View demo Download

Comments to “PHP Upload Image to Database with MySql”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page