Reputation: 658
How can i restore or access MySQL blob field so I can preview it as HTML using PHP codes? Is there an available function in PHP so I can store as jpeg those blob field.
Upvotes: 2
Views: 2658
Reputation: 7572
The code presented above is vulnerable to SQL injection attacks and will in any case fail at the first byte of the JPEG that happens to match the ASCII code for a quote mark (which should happen quite quickly). I do see your comment that you "might" want to escape the data, but it should be emphasized that in a big binary file, there will almost certainly be a byte that matches the quote mark. It's not "just in case," it's practically every case.
Use mysql_real_escape_string() on the JPEG data and the id parameter (which comes from the user, who may be malicious). Better yet, use PDO and parameter substitution to avoid that mess.
Also, the content type must be image/jpeg, not img/jpeg.
Upvotes: 1
Reputation: 6470
Storing is easy. Assuming you have a mysql table with BLOB field for pictures....
Once the image is uploaded you get the contents of the file into memory and then insert into the blob field.
<?php
$file = '/tmp/MyImg.jpg';
// you migh want to escape it just in case
$data = file_get_contents($file);
// Insert into database
$sql = "INSERT INTO my_picture_table (`picture_blob_field`) VALUES ('$data');"
?>
Retrieving is fairly simple as well. It is simpler to make a separate file to load images from blob.
<?php
// file = getPicture.php
$id = (int) $_GET['id'];
$sql = "SELECT `picture_blob_field` FROM `my_picture_table` WHERE `id` = $id"
// query the db
// store data into var $picData
// Set the content type and print the data.
header("Content-type: img/jpeg");
echo $picData;
?>
This is all you have to do... Now in HTML page just create an
<img scr="getPicture.php?id=PICTURE_ID alt="blah blah" />
Note that above example is for JPEG type, store the file type in the db and then use it to specify file type with header("Content-type: img/xxx")
Hope this solved your problem.
I found an example/tutorial on storing images in mysql. If above is not clear look through the code (its paginated, so look at the other pages)
Upvotes: 3