12 November 2010

Easy to understand tutorial on how to upload, store and display images in mysql database.

Uploading Form and Table:

First off we need a HTML form that uploads images. If you are not familiar with making one then visit: HTML Upload Form

Then we need to create a table to our database. Table should contain unique identifier, blob for file data and image type.
Source code viewer
  1. CREATE TABLE IF NOT EXISTS `images` (
  2. `image` mediumblob NOT NULL,
  3. `type` varchar(255) NOT NULL,
  4. PRIMARY KEY (`id`)
Programming Language: MySQL
Easy to understand tutorial on how to upload, store and display images in mysql database.

Uploading Data:

Now we need a script to receive and store the image.
Source code viewer
  1. #get the image files content and type
  2. $content = file_get_contents($_FILES['file_name']['tmp_name']);
  3. $type = $_FILES['file_name']['type'];
  4. #upload $content and $type
  5. $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
  6. if (!$link) die('Could not connect: ' . mysql_error());
  7.  
  8. $query = 'INSERT INTO images (type, content) VALUES (`'.$type.'`, `'.$content.'`)';
  9.  
  10. $result = mysql_query($query);
  11. if ($result) {
  12. echo 'Image successfully uploaded.';
  13. }
  14.  
  15. mysql_close($link);
Programming Language: PHP

Displaing the image:

First you have to get image from database. Then set header for right content type. Print the content and done.
Source code viewer
  1. <?php
  2. $id = 1;
  3. $result = mysql_query('SELECT type, content FROM people WHERE id = '.$id);
  4. if (!$result) {
  5. echo 'Could not run query: '.mysql_error();
  6. }
  7. $row = mysql_fetch_row($result);
  8.  
  9. header('Content-type: '.$row[0]); #type
  10. echo $row[1]; #content
  11. ?>
Programming Language: PHP
If you use get you can make images change by url variable.