This tutorial expands on another database/image how-to How to Store Images in Mysql Database. In the Images In tutorial I showed you the basic steps to opening a file (your image file) and reading it into a variable ($img), converting that file using php's base64_encode() function, and sticking that file into a Mysql database. Now, you will learn how to bring those images back out of a Mysql database, and render them to a web browser.
This Tutorial will cover two different ways to fetch and render images from a MySQL database
CREATE TABLE `pictures` ( `id` int(8) NOT NULL AUTO_INCREMENT, `pic` blob NOT NULL, `ext` varchar(4) NOT NULL, `gender` varchar(7) NOT NULL, PRIMARY KEY (`id`), KEY `id` (`id`) )
Now - Create a directory on your web server and call it "test"
Create a file named "test01.php" in the"test" directory, and copy the Uploading Images Script to it.
Copy test image intotest folder.
Create a file named "test02.php", copy the contents of the PHP Image Rendering Script to it, then save it to the test directory.
Method 1# - rendering database images with php and MySQL.
This method determines what type of image is retrieved from the database, and uses the php header() function to setup and render the images.
Create a file named "test03.php" copy the Second Method Script to it. (See below)
Create a file named " db_connection.php" copy the Database Connection Parameters below
Create a file named "test04.php" copy the HTML for test_04.php (See below)
After building the database, and uploading all the example files and images to your server:
1. Navigate and execute test01.php script
testpic.jpg will be uploaded to your MySql server with an id of "1".
2. Click Method 1 to view your image. This particular script sends headers and render the jpg image via php script.
3. Next - Hit the Browser Back Button and click Method 2.
Notice that on the test04.php page, I inserted src="test_03.php" in the img tag. Doing this causes the test_03.php script to execute; the img tag sets up the headerfor theweb-browser.