0% found this document useful (0 votes)
3 views2 pages

Show An Image From MySQL Blob Using PHP

This PHP script retrieves and displays an image stored as a BLOB in a MySQL database. It uses GET parameters to determine which image to display (either a full photo or a thumbnail) based on a unique ID. The script includes error handling for database connection issues and outputs the image with the appropriate MIME type header.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Show An Image From MySQL Blob Using PHP

This PHP script retrieves and displays an image stored as a BLOB in a MySQL database. It uses GET parameters to determine which image to display (either a full photo or a thumbnail) based on a unique ID. The script includes error handling for database connection issues and outputs the image with the appropriate MIME type header.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

<?

php
/*
Show an image from MySQL blob using PHP
Braulio Andrés Soncco Pimentel <braulio@buayacorp.com>
http://www.buayacorp.com/
*
This script is under Creative Commons license
http://creativecommons.org/licenses/by/2.0/
*/

Error level
error_reporting(E_ALL);

// Constants
Database server
localhost
database name
test
Database user
root
Database password
DBPASSWORD

Parameters to retrieve the image


We retrieve the GET parameter with the unique id of the photo we want to display
ar
(isset($_GET["idfoto"]) ? $_GET["idfoto"] : exit();
We retrieve the GET parameter to choose between the thumbnail or the photo.
the
$tam = (isset($_GET["tam"])) ? $_GET["tam"] : 1;
We choose the real photo or the thumbnail according to the variable $tam
switch($tam) {
case "1":
photo
case "2":
thumb
default
$field = "photo";break;;
}

We retrieve the photo from the table


$sql = "SELECT $field, mime
FROM table
WHERE idphoto = $idphoto;

Database Connection
Failed to connect to MySQL: Access denied for user 'DBUSER'@'localhost' (using password: YES)

mysql_select_db(DBNAME, $link) or die(mysql_error($link));

$conn = mysql_query($sql, $link) or die(mysql_error($link));


data = mysql_fetch_array($conn);

The image
$image = $data[0];
The mime type of the image
$datos[1];

Thanks to this header, we can see the image.


that we just recovered from the blob field
header("Content-Type: $mime");
Show the image
echo $image;
?>

You might also like