Well, in order to store image-data in a database, you need to use a BLOB field which stores binary data.
You should be familiar with:
- Uploading files using HTML-Forms
- Inserting Rows into databases
First you should create a database-table with at least four fields:
- imageid (INT-field: auto-incremented)
- imagedata (BLOB-field: the image-data.)
- imagesize (INT-field: the size (in Bytes) of the image)
- imagetype (VARCHAR-field: holds the file-extension of the image)
Uploading the image to the databaseHere's what you need to do FOR UPLOADING:
1. Take the image you want (presumably uploaded from an HTML form) and read the contents using something like file_get_contents() -- this will be a variable and we will name it "$image_data". We will also define 2 more variables which will hold the size of the image, and the file-extension of the image.
1.1.
- Code: Select all
$image_data = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image_size = $_FILES['image']['size'];
$image_type = mysql_real_escape_string(end(explode('.', $_FILES['image']['name'])));
***Note: $_FILES['image'] comes from the HTML-Form Element: <input type="file" name="image" />
2. Insert a new row into a database
2.2
- Code: Select all
mysql_query("INSERT INTO `image_table` (`imagedata`, `imagesize` `imagetype`) VALUES ('".$image_data."', ".$image_size.", '".$image_type."')");
Retrieving the image from the databaseYou need to define a $_GET variable which will hold the image-id (we'll call this "$_GET['imageid']")
Here's what you need to do FOR READING:
1. Using the $_GET variable we defined, we can retrieve the image (specified by $_GET['imageid']) from the database
1.1
- Code: Select all
$result = mysql_query("SELECT `image_data`, `image_size`, `image_type` FROM `image_table` WHERE `imageid`=".(int)$_GET['imageid']);
2. Check if a row corresponding to the value of $_GET['imageid'] was found. If a row was found, then we need to output the image-data
2.1
- Code: Select all
if(mysql_num_rows($result) == 0){
echo 'Image not found';
} else {
$row = mysql_fetch_assoc($result);
header('Content-type: image/'.$row['image_type']);
header('Content-Length: '.$row['image_size']);
echo stripslashes($row['image_data']);
}
This method will enable to retrieve the image using the HTML IMG-tag like so:
- Code: Select all
<img src="http://example.com/get_image.php?imageid=42" />
Note: get_image.php is just an arbitrary name. You can make it whatever you want.
Note: The code I have provided is only for clarification purposes. It is not 100% secure with the exception of escaping strings and type-casting variables.