Why store binary files in MySQL using PHP?
You may want to allow users to upload files to your PHP script or store banner images from advertisers inside of your SQL database. Instead of creating and using a messy directory structure it may be more suitable to store them directly in your SQL database along with the advertiser or user information.
Reasons to store your images (binary files) in a database:
- Storing in a database allows better security for your files and images.
- Eliminates messy directory and file structures (this is especially true when users are allow to contribute files).
- Files/Images can be stored directly linking to user or advertiser information.
You may want to reconsider storing your binary files in the database. Here are some reason you may not want to:
- You can't directly access your files using standard applications such as FTP.
- If you database becomes corrupt, so do your files.
- Migrating to a new database is made more difficult
- Pulling images from a database and displaying them is slower than using file access.
Note: all of the banners and user attachments that CodeCall has are stored directly in MySQL.
Creating the Database and Table
Using the console we will access MySQL and create a database and table for our binary upload PHP script. Using a tool such as PHPMyAdmin can make this task a bit easier. If your webhost has cpanel or Plesk then you probably have access to PHPMyAdmin. If your host does not you might want to consider hosting from ToastedPenguin.com.
First login to MySQL:
# mysql -u root -pEnter Password: ******
Replace the user root with your username for MySQL. Since I'm running this on my local machine I will access the database using the root account via the console and PHP Script. This is not recommended and you should not access your database in a public environment, such as the internet, using the root user, ever!
Now create the database:
mysql> CREATE DATABASE binary;
Press Enter, you should see results similar to:
Query OK, 1 row affected (0.00 sec)
Lets create the table now:
mysql> CREATE TABLE tbl_images (> id tinyint(3) unsigned NOT NULL auto_increment,> image blob NOT NULL,> PRIMARY KEY (id)> );
What is a BLOB?
Above we created two tables, one the primary ID (of the row/entry) and the binary BLOB. A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types are TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the values they can hold. The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four BLOB types and have the same maximum lengths and storage requirements.