How to Upload Image into Database and Display it using PHP


In modern web applications, it is common to store images in databases for various reasons, such as security, easy management, and scalability. PHP, being a popular server-side scripting language, provides an easy way to upload images to databases and display them on the web pages.

In this article, we will learn How to Upload Image into Database and Display it using PHP. PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open-source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

In the below article, we have demonstrated the examples with the complete process to implement the file upload functionality in the web application and the following functionality will be implemented.

  • HTML form to upload an image.

  • Upload an image to the server using PHP.

  • Store file names in the database using PHP and MySQL.

  • Retrieve images from the database and display on the web page.

Approach to upload image into database in PHP

To create a database table, make sure you have installed WAMP or XAMP server or use a tool like phpMyAdmin- a web-based application that allows you to manage MySQL databases. Here are the steps to create a table using phpMyAdmin.

Step 1: Create a Database and Table

First, we will create a database with a name like ‘tutorialspoint’. Or may use an existing database or create a new one.

After which, we will create a table in the database that will store the image data. The table must have a column of type "BLOB" (Binary Large Object), which can store large binary data, such as images.

For example, below is an SQL query to create a table named "images" with three columns: "id", "name", and "data". The "id" column is an auto-incrementing primary key, the "name" column is used to store the filename of the image, and the "data" column is used to store the binary data of the image.

To create a table use the following code in the SQL panel of your PHPMyAdmin.

CREATE TABLE images (
   id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
   name VARCHAR(255) NOT NULL,
   data LONGBLOB NOT NULL
);

Step 2: Create an HTML Form to Upload an Image

The next step is to create an HTML form that allows users to select and upload an image. The form must have an input field of type "file", which allows users to browse and select an image file from their computer. When the form is submitted, the selected image file will be sent to the server for processing.

<form method="post" action="upload.php" enctype="multipart/form-data">
   <input type="file" name="image" />
   <input type="submit" name="submit" value="Upload" />
</form>

Note that the form has three important attributes:

The "method" attribute is set to "post" to indicate that the form data will be sent to the server using the HTTP POST method.

The "action" attribute is set to "upload.php", which is the name of the PHP script that will handle the image upload.

The "enctype" attribute is set to "multipart/form-data", which is necessary when uploading files.

Step 3: Processing the Uploaded Image

The next step is to create a PHP script that will process the uploaded image and store it in the database. The script must first check if an image file has been uploaded and, if so, extract its binary data and store it in the database.

Here is an example PHP script named "upload.php" that does this:

<?php
   // check if an image file was uploaded
   if(isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
      $name = $_FILES['image']['name'];
      $type = $_FILES['image']['type'];
      $data = file_get_contents($_FILES['image']['tmp_name']);
      // connect to the database
      $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
      // insert the image data into the database
      $stmt = $pdo->prepare("INSERT INTO images (name, type, data) VALUES (?, ?, ?)");
      $stmt->bindParam(1, $name);
      $stmt->bindParam(2, $type);
      $stmt->bindParam(3, $data);
      $stmt->execute();
   }
?>

Step 4: Displaying the Image on a Web Pag

The final step is to create a PHP script that retrieves the image data from the database and displays it on a web page. The script must first retrieve the image data from the database using a SELECT statement and then output the image data as binary data using the appropriate MIME type.

Here is an example PHP script named "display.php" that does this:

<?php
   // get the ID of the image from the URL
   $id = $_GET['id'];
   // connect to the database
   $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
   // retrieve the image data from the database
   $stmt = $pdo->prepare("SELECT name, type, data FROM images WHERE id=?");
   $stmt->bindParam(1, $id);
   $stmt->execute();
   // set the content type header
   header("Content-Type: image/jpeg");
   // output the image data
   $row = $stmt->fetch(PDO::FETCH_ASSOC);
   echo $row['data'];
?>

Step 5: Displaying the Image on a Web Page

To display the image on a web page, we can use an HTML "img" tag and set the "src" attribute to the URL of the PHP script that outputs the image data.

Here is an example HTML code that displays the image with ID 1:

<img src="display.php?id=1" />

When the page is loaded, the "display.php" script is called with the ID parameter set to 1, and the image data is outputted as binary data, which is displayed by the "img" tag.

Conclusion

Uploading images to a database and displaying them on web pages using PHP is a straightforward process that involves creating a database table with a BLOB column, creating an HTML form to upload the image, creating a PHP script to process the uploaded image, and store it in the database, creating a PHP script to retrieve the image data from the database and output it as binary data, and finally, displaying the image on a web page using an HTML "img" tag. By following these steps, developers can easily implement image uploading and displaying functionality in their web applications.

Updated on: 14-Jul-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements