PHP Quick Tip: Someone asked me how to display an image stored in a MySQL database using PDO. Here’s how I did it. In this code, we will use two files – index.php and source.php and a database table with sample image data stored.
Please note that I used BLOB data type for storing my images, it can handle up to 64KiB of data. If you want larger storage for each of your images, you can use LONG BLOB that can handle up to 2,048KiB of data.
database:
index.php – This will call the image rendered by source.php using the <img> tag. The code goes like this:
- CREATE TABLE IF NOT EXISTS `images` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(32) NOT NULL,
- `data` blob NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;
index.php – This will call the image rendered by source.php using the <img> tag. The code goes like this:
source.php – This will do the query of selecting the image based on the given ID parameter. PDO code look something like this:
- <?php
- //include database connection
- include 'db_connect.php';
- //select the image
- $query = "select * from images WHERE id = ?";
- $stmt = $con->prepare( $query );
- //bind the id of the image you want to select
- $stmt->bindParam(1, $_GET['id']);
- $stmt->execute();
- //to verify if a record is found
- $num = $stmt->rowCount();
- if( $num ){
- //if found
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- //specify header with content type,
- //you can do header("Content-type: image/jpg"); for jpg,
- //header("Content-type: image/gif"); for gif, etc.
- //display the image data
- print $row['data'];
- exit;
- }else{
- //if no image found with the given id,
- //load/query your default image here
- }
- ?>
I got this output:
Click to enlarge. |
How to resize this image output? You can just do it the normal way, for instance:
<img src='source.php?id=1' width='300' height='300' />
If you want to download this code:
The Code of a Ninja Resources
For FREE programming tutorials, click the red button below and subscribe! :)
website