Tuesday, December 23, 2008

Inserting Binary data into MySQL database using Php

A simple script which can help to store any binary data to you MySQL database. You can add any type of binary data eg word document, Excel spreadsheet, PDF file , an image or a video in through it. I will use MySQL's LONGBLOB data type. it support at most a data of 4GB.

schema
CREATE TABLE `mydata` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`data` LONGBLOB NOT NULL,
`fname` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB
create the above table before using the script

upload_file.php

<?php
if($_FILES['myfile']['tmp_name']!="")
{
if(mysql_connect("localhost","root",""))
{
if(mysql_select_db("mydb"))
{
$fname=$_FILES['myfile']['name'];
$tname = $_FILES['myfile']['tmp_name'];
$fsize = $_FILES['myfile']['size'];
$data=file_get_contents($tname);
//to escape all binary data which can make mysql mad
$data = mysql_real_escape_string($data);
if(mysql_query("Insert into mydata (data,fname) values('$data','$fname')"))
{
echo "File inserted successfully";
}
else
{
echo "Error occured ".mysql_error();
}
mysql_close();
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="UPLOAD">
</form>
usage: upload_file.php

download_file.php
if(mysql_connect("localhost","root",""))
{
if(mysql_select_db("mydb"))
{
$id = (int)$_GET['id'];
$result=mysql_query("Select * from mydata where id = {$id}");
if($row=mysql_fetch_array($result))
{
Header( "Content-type: application/octet-stream");
Header( "Content-Disposition: inline; filename={$row['fname']}");
echo ($row['data']);
}
else
{
echo "File doesn't exist with above id";
}
}
}
?>

usage: download_file.php?id=2

enjoyy ... for any problem with the script leave your comments!

2 comments:

  1. It is not diplying only pdf file

    doc and excel file not working with this code properly

    ReplyDelete