Wednesday, November 28, 2007

Store and saving binary data (images, coding, etc.) into MySql Database with PHP

An interesting topic in Mysql is to use the database to store binary data, such as images or html code. The first step is to create the database:

CREATE TABLE binary_data (
id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
descripction CHAR(50),
bin_data LONGBLOB,
filename CHAR(50),
filesize CHAR(50),
filetype CHAR(50)
);


The following script can be used to insert binary objects in the database from a browser. Note that the tag is used input type = "file" a form html to upload a file.


<HTML>
<HEAD><TITLE>Store and saving binary data (images, coding,
etc.) into MySql Database with PHP
</TITLE></HEAD>
<BODY>
<?php
if ($submit) {
//
Code that runs if I press the submit button
MYSQL_CONNECT( "localhost", "root", "password");
mysql_select_db( "binary_data");
$data = addslashes(fread(fopen($form_data, "r"),
filesize($form_data)));
$result=MYSQL_QUERY( "INSERT INTO binary_data(description,
bin_data,filename,filesize,filetype) ". "VALUES
('$form_description','$data',
'$form_data_name',
'$form_data_size','$form_data_type')");
$id= mysql_insert_id();
print "<p>Database ID: <b>$id</b>";
MYSQL_CLOSE();
} else {
// else
bring up the form for new data:
?>
<form method="post" action=" <?php echo $PHP_SELF; ?>"
enctype="multipart/form-data">
File Description:<br>
<input type="text" name="form_description" size="40">
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>
Upload file to the database:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>
<?php
}
?>
</BODY>
</HTML>

Note the use of $ PHP_SELF predefined variable that contains the name of the script. This form is called himself regardless of the name that comes to the file.

The following script (getdata.php) can be used to recover data from the database, noting that the script expects to receive the variable $ id with id register to recover from the table.

<?php
if($id) {
@MYSQL_CONNECT( "localhost", "root", "contraseña");
@mysql_select_db( "binary_data");
$query = "select bin_data,filetype from binary_data where id=$id";
$result = @MYSQL_QUERY($query);
$data = @MYSQL_RESULT($result,0, "bin_data");
$type = @MYSQL_RESULT($result,0, "filetype");
Header( "Content-type: $type");
echo $data;
};
?>

To use an image that is obtained from the database can be used:


<img src="getdata.php?id=3">

Note as he passes the variable id to script to know what is the record to retrieve the base.



No comments: