Generally, once we upload image enter PHP, the uploaded image is stored during a directory of the server and therefore the respective image name is stored into the database. At the time of display, the file is retrieved from the server and therefore the image is rendered on the online page. But, if you don’t want to consume the space of the server, the file is stored within the database only. You’ll upload a picture without storing it on the server using the MYSQL database. It’s very easy to store and retrieve images from the database using PHP and MYSQL.
If you’re concerned about the server space and wish to free space on your server, you’ll insert a picture enter the database without upload it to the directory of the server. This procedure helps to optimize the server space because the image file content is stored within the database instead of the server. During this tutorial, we’ll show you ways to store image file into the MYSQL database and retrieve images from the database using PHP.
Insert Image file in MYSQL
MYSQL features a BLOB (binary large object) data type which will hold an outsized amount of binary data. The BLOB data type is ideal for storing image data. In MYSQL, four BLOB types are available – TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.
Create Database Table
To store the file content, a table is required within the database. The following SQL creates an images table with the LONGBLOB data type field within the MYSQL database.
Database Configuration (dbconfig.php)
The dbconfig.php file is employed to attach and select the database. Specify the database host ($dbhost), username ($dbusername), password ($dbpassword), and name ($dbname) as per your MYSQL database credentials.
Image Upload Form
Create an HTML form with a file input field to pick a picture file for upload. Confirm the <form> tag contains the following attributes.
Tore Image enter Database (upload.php)
The upload.php files handles the image uploads and database insertion process.
- Check whether the user selects a picture file to upload.
- Retrieve the content of image file by the tmp_name using PHP file_get_contents() function.
- Insert the binary content of the image within the database using PHP and MYSQL.
- Show the image uploading status to the user.
Retrieve image from database (view.php)
In the view.php file, we’ll retrieve the image content from the MYSQL database and list them on the online page.
The data, charset, and base64 parameters within the SRC attribute are wont to display image BLOB from MYSQL database.