Storing Images in a Database
This tutorial teaches you how to upload images into a MySQL database using PHP. Even though it sounds complicated, it is fairly simple and has many practical applications. One example of an application would be Forum User Images. Take user avatars for example. Its impractical to upload avatar files to one common folder, because chances are sooner or later two users will have the same name for an avatar, and either one avatar will be overwritten, or the other not accepted, causing trouble. Image Databasing solves this problem by inserting the image data into its own unique row in a table, each assigned with an ID number instead of a filename. Images can then be called from the database and be view using one PHP file for all images. How are they inserted into the database? By converting the data to base64. If you’re confused, please bear with me, you will understand it soon.
There will be 3 PHP files in this tutorial:
readdir.php – this puts all the images in a folder into the database
image.php – the actual image script that displays the imag
view.php – an example file that shows you how to call the image
Base 64 is an encoding for binary data as described as a means of encoding email bodies in the IETF’s MIME RFC. Base64 consists only of 64 encoding characters (A-Z, a-z, 0-9, +, /) that are a subset of US-ASCII. You can find out more here.
PHP includes 2 base64 functions – base64_decode() and base64_encode(). You can find out more about each one here and here respectively.
Creating the Image Database
First, create a MySQL database called base64imgdb (this is the name that will be used throughout the tutorial). Alternatively, you can use an existing database and just add the tables.
Second, create a table called images with two rows. Name the first one imgid, and give it the parameters TYPE: INT EXTRA: auto_increment, and check the circle under Primary. Name the second sixfourdata, and make it TYPE: LONGTEXT. Here is the SQL code you can execute to create the table:
|constant connection to the MySQL database instead of creating multiple ones. Here is the PHP code, you will need to change the username and password parts:
Next we need to open the directory, where