Storing Images/Binary Files to mySQL in PHP

It is possible for us to store/save our images (binary files) into a mySQL database in PHP. In this article, we will discuss about “how to store images, audio, or another binary files into mySQL database with PHP script”. But, before we continue to the further step, you might want to consider some reason of why we should and why we shouldn’t store binary files in a database:

Reasons to store your images (binary files) in a database:

  1. Storing in a database allows better security for your files and images.
  2. Eliminates messy directory and file structures (this is especially true when users are allow to contribute files).
  3. 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:

  1. You can’t directly access your files using standard applications such as FTP.
  2. If you database becomes corrupt, so do your files.
  3. Migrating to a new database is made more difficult
  4. Pulling images from a database and displaying them is slower than using file access.

After considering above reasons, you may continue to the first step of this tutorial.

Database Type and Connection

I assume that you already create a mySQL database named “binary”. 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.

You’ve now created your database and are ready to upload binary files to it. In this case, images. Next we will create a simple upload script.

Creating the HTML

Creating the user interface where you or your visitors will upload files is very simple. Using basic HTML and relying on the browser to do most of the heavy lifting you can easily create an upload form. Here is the one we will use:

HTML Code:
<form enctype="multipart/form-data" action="insert.php" method="post" name="changer">

<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">

<input value="Submit" type="submit">

Copy this code into a file and save it as add.html

The code above allows the uses to browse for a file and select any image/jpeg file type. Once selected and the submit button is pressed the image contents are forwarded to PHP script, insert.php

Inserting the Image into MySQL

Create a new file named insert.php. If you change the name of this file you will also need to change the action=”” part in your HTML file above. Open the file in your favorite text editor or PHP IDE.

Write or copy/paste this code into your file:

PHP Code:


// Create MySQL login values and
// set them to your login information.
$username = "YourUserName";
$password = "YourPassword";
$host = "localhost";
$database = "binary";

// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!
$link) {
die(
'Could not connect: ' . mysql_error());
}

// Select your database
mysql_select_db ($database);



The above code sets your connection variables, creates a connection to MySQL and selects your database (binary if you followed my instructions above). Next we need to read the form data and insert it into the database.

PHP Code:



// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {

// Temporary file name stored on the server
$tmpName = $_FILES[‘image’][‘tmp_name’];

// Read the file
$fp = fopen($tmpName, ‘r’);
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);

// Create the query and insert
// into our database.
$query = “INSERT INTO tbl_images “;
$query .= “(image) VALUES (‘$data’)”;
$results = mysql_query($query, $link);

// Print results
print “Thank you, your file has been uploaded.”;

}
else {
print “No image selected/uploaded”;
}

// Close our MySQL Link
mysql_close($link);
?>

The PHP code above takes the user selected image, reads it with fopen and stores the data in a variable named $data. The binary data is then inserted into our database for retrieval at a later time.

Save the file above and access add.html via your browser. Select an image file and upload it.

I will post the next stage of this tutorial: “How to read binary data from database

Andi Setiawan

Loving husband - Caring Father - Slap bet Commissionaire (I wish) find my complete profile on: http://andisetiawan.com/about-me http://facebook.com/andiim3 - http://gplus.to/andiim3 - http://andiim3.com

Share
Published by
Andi Setiawan

Recent Posts

Dedicated Blog for Dobby and Luna

Dobby and Luna have been part of our lives for the past years. They have…

2 years ago

Demo Site For My Projects

In the year 2021, I've completed some paid projects. Some of them are more technical,…

2 years ago

GlassTime – Glassmorphism WordPress Theme

Based on the GlassTime Bootstrap template, here I present glassmorphism WordPress Theme free to download.This…

3 years ago

GlassTime : Glassmorphism Responsive HTML5 Template

This HTML5 template is using Glassmorphism UI design language which is now trending for 2021…

3 years ago

Daftar Desa, Kecamatan, dan Kode Pos Buleleng – Bali

KecamatanKode POSBanjar81152Buleleng81119Busungbiu81154Gerokgak81155Kubutambahan81172Sawan81171Seririt81153Sukasada81161Tejakula81173Klik pada nama kecamatan untuk melihat daftar desa masing-masing. Sumber: kodepos.andiim3.com

3 years ago

Ninja diganti ADV

Ada yang bilang "semuanya akan mati matic pada akhirnya". Bener aja, sekarang tuntutan transportasi sehari-hari…

4 years ago

This website uses cookies.