Retrieve binary
file from MySQL database
Before you start this tutorial, please read the following
lessons:
- Insert binary
file using PHP code
- using phpMyAdmin
insert binary file
- Using form
insert binary file into MySQL
This lesson will show you how to retrieve binary files you saved
in the above lessons.
Retrieve binary file
Assume you saved a PDF file to the database. It takes 2 step to
get saved PDF file from database.
First step, you create a HTML file, like the following:
<html>
<body>
<a href="download.php">My PDF </a>
</body>
</html>
The above code displays a link in the browser. Once clients click
on the link, download.php will be called and fetch PDF file from
MySQL.
Second step, write download.php file. Here is the PHP code for downloading
PDF file from MySQL:
<?php
//connect to database
$username="yourusername";
$password="yourpassword"; //input
your password here.
$database="yourdatabase";
//connect to database
$link=mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("<b>Unable to specified
database</b>");
//query database
$query = "SELECT image FROM youtablename WHERE id = 10";
$result = mysql_query($query) or die('Error, query failed');
$content=mysql_result($result,0,"image");
//send pdf to requesting page
header("Content-type: application/pdf");
echo $content;
mysql_close($link); //close database connection
?> |
In the above example, we assume the PDF file is saved in table named
youtablename with a id =10.
Please note that header("Content-type:
application/pdf"); must be put before echo
$content; Otherwise, it won't work properly. header() function
sends a HTTP header to browser, which tells the browser what kind of
file it is sending.
If you retrieve a .jpg file, you need use:
header("Content-type:
image/jpg");
If you retrieve a .gif file, you need use:
header("Content-type: image/gif");
If you retrieve a .mid file, you need use:
header("Content-type: audio/mid");
....
Use GET method in downloading code
The above code is very easily changed to GET style. So download.php
could be used for download any files without changing a bit.
First change your HTML code to:
<html>
<body>
<a href="download.php?id=10">My PDF </a>
</body>
</html>
Second change your download.php to the following
<?php
//connect to database
$id=$_GET['id'];//get id
$username="yourusername";
$password="yourpassword"; //input your password
here.
$database="yourdatabase";
//connect to database
$link=mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("<b>Unable to specified database</b>");
//query database
$query = "SELECT image FROM youtablename WHERE id = $id";
$result = mysql_query($query) or die('Error, query failed');
$content=mysql_result($result,0,"image");
//send pdf to requesting page
header("Content-type: application/pdf");
echo $content;
mysql_close($link); //close database connection
?> |
download.php will take id parameters from requesting page and becomes
more flexible.
|