Mega Code Archive

 
Categories / Php / MySQL Database
 

How to show images stored in a database

There have been a number of questions lately about storing images in a db table and then how to show them correctly. The problem is that the header for images needs to be set correctly for the binary data to be show correctly. Here are the two working pages (tested my machine (xp, apache2, php4.3.9 mysql 4.01.x) In the areas for the db query you will see the notation $result = connect(sql); connect is a custom function to handle all db interatction that is separate from the pages and included in the conn.php file. There is another example with that function in my previously posted code samples. <?php // show_desc.php require("conn.php"); // you may have to modify login information for your database server $query = "select description, id from binary_data "; $result = connect($query); while ($rows = MYSQL_FETCH_ARRAY($result)) { echo $rows['description']; echo "<br><br>"; echo "<img src=\"show_image.php?id=".$rows['id']."\">\n"; }; ?> <?php //show_image.php require("conn.php"); //check to see if the id is passed if(isset($_GET['id'])) { $id=$_GET['id']; $query = "select bin_data, filetype from binary_data where id=$id"; //echo $query; $result = connect($query); $row = mysql_fetch_array($result); { $data = $row['bin_data']; $type = $row['filetype']; } if ($type=="pjpeg") $type = "jpeg"; Header( "Content-type: $type"); echo $data; } ?> Database table: CREATE TABLE binary_data ( id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY, description CHAR(50), bin_data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50) );