Insert
binary file into MySQL (BLOB) using PHP progaming
Before you start this lesson, I assume that you finished reading
the following tutorials:
- install phpmyAdmin, mysql
, php
- Create Database by using phpMyAdmin
- Working with forms
- Insert Form Data into Database
- Retrieve data from
Database
- Insert binary file into
MySQL using phpMyAdmin
This lession will demonstrate how to use PHP programming insert
binary files into MySQL database BLOB column.
Insert Images into MySQL
There are 3 steps to insert binary files into MySQL BLOB columns:
- Open database connection
- Get binary file content
- Insert file into database
Connect to Database
From lesson: Insert Form Data
into Database and Retrieve
data from Database we already knew how to open database connection.
We repeat here:
<?php
$username="root";
$password="yourpassword"; //input your password
here.
$database="phonebook"; //your database here
//connect to database
$connect=mysql_connect(localhost,$username,$password);
//select database
@mysql_select_db($database) or die("<b>Unable to specified
database</b>");
Get binary file content
//get images
$myimage = "c:\yourpath\yourimagefile.gif";
$image = file_get_contents($myimage);
$content=addslashes($image);
file_get_contents get $myimage
binary file content in string. addslashes()
function will returns a string with backslashes before characters
that need to be quoted in database queries. So those special characters
in image file could be properly stored in database.
You may give a URL to $myimage like the following
$myimage = "http://www.yourwebsite.com/images/yourimage.gif";
Insert into databse
//query databae
$query="INSERT INTO gallery (image) VALUES ('$content')";
@mysql_query($query) or die('Error, insert query failed');
//close connection
mysql_close($connect);
INSERT INTO gallery (image)
VALUES ('$content') will
insert $contenst into gallery table image column.
Put it together:
<?php
$username="root";
$password="yourpassword"; //input
your password here.
$database="phonebook"; //your database here
//connect to database
$connect=mysql_connect(localhost,$username,$password);
//select database
@mysql_select_db($database) or die("<b>Unable to specified
database</b>");
//get images
$myimage = "c:\yourpath\yourimagefile.gif";;
$image = file_get_contents($myimage);
$content=addslashes($image);
//query databae
$query="INSERT INTO gallery (image) VALUES ('$content')";
@mysql_query($query) or die('Error, insert query failed');
//close connection
mysql_close($connect);
?>
There are other alternative ways to insert binary files
into MySQL:
- Using php
programming insert binary files into MySQL
- Using
HTML Form and php progamming insert binary files into MySQL(local
and remote)
- Using PhpMyAdmin
insert binary files.
|