No. You need to get the file contents of the image or else it won't work. I also strongly advise you store the MIME type of the image as well if you're going to do this, so you could decode it.. Storing images in the database isn't bad practice unless you have a massive amount of storage data, in which case it is more efficient to store your images in your file system.
First, you need to get the file contents of the image. Then you need to addslashes so that it doesn't interfere with the single quote character ( ' ) that you have in your SQL query. You should also store the MIME type of the iamge.
PHP Code:
<?php
$file_name = "images/mouse.jpg";
$file = file_get_contents($file_name);
$file = addslashes($file);
$mime_type = mime_content_type($file_name);
?>
The contents of file is what you need to store:
Code:
INSERT INTO `products` (`serial`, `name`, `description`, `price`, `picture`, `mimeType`) VALUES
(1, 'View Sonic LCD', '19" View Sonic Black LCD, with 10 months warranty', 250, '$file', '$mime_type'),
(2, 'IBM CDROM Drive', 'IBM CDROM Drive', 80, '$file', '$mime_type'),
(3, 'Laptop Charger', 'Dell Laptop Charger with 6 months warranty', 50, '$file', '$mime_type'),
(4, 'Seagate Hard Drive', '80 GB Seagate Hard Drive in 10 months warranty', 40, '$file', '$mime_type'),
(5, 'Atech Mouse', 'Black colored laser mouse. No warranty', 5, '$file', '$mime_type'),
(6, 'Nokia 5800', 'Nokia 5800 XpressMusic is a mobile device with 3.2" widescreen display brings photos, video clips and web content to life', 299, '$file', '$mime_type');
To decode your image, you need to determine what image you need to recreate. You can do this by using GD library functions. Consider the example below, which selects a product with the serial = 9 (Note: Only select one row for this). First you need to output the mime type to the browser so it knows what it needs to decode. Then output the image data.
PHP Code:
<?php
$details = mysql_query("SELECT picture, mimeType FROM `products` WHERE serial = '9'") or die(mysql_error());
$row = mysql_fetch_array($details);
header("Content-Type: $row['mimeType']");
echo $row['picture'];
?>
And that's it. That script will decode and show the image. Keep in mind that you can't print out any other content, since the mime type of that page is now an image.
Bookmarks