Reputation: 23
I'm doing something wrong while inserting or retrieving a image in/from a mysql blob field. I looked at a lot of questions allready asked here at stackoverflow, but cant get mine to work.
field:
<input type="file" name="filename" id="filename" />
inserting code:
$img = chunk_split(base64_encode(file_get_contents(
$_FILES['filename']['tmp_name']
)));
$insrtSQL = "
INSERT INTO table (s_id, s_name, s_image, s_text, s_link, t_id)
VALUES ('a', 'a', '$img', 'a', 'a', 'a')
";
echoing code
<?php
echo '<img src="data:image/jpeg;base64,' .
base64_encode($row_Sss['s_image']) .
'" width="290" height="290">'
?>
I know i should use MySQLi or PDO instead, but thats not an option for now. What am I missing? or doing wrong?
Upvotes: 1
Views: 1582
Reputation: 182
Wait... Are you BASE64 encoding your data - twice?
First you do a base64_encode() on the uploaded file, then you select it from your table later on and echo() it yet again with base64_encode(). Try removing the base64_encode when doing your echo, and also try omitting the chunk_split() command when inserting data into the table.
Also, you don't have to base64 encode any data if you're looking to store binary data into a mySQL blob field, just do something this:
$img = mysql_real_escape_string(file_get_contents($_FILES['filename']['tmp_name']));
Then you may echo it with base64_encode() in your HTML.
Remember, since you're storing large chunks of data in your table, avoid using "SELECT * " queries, as this will significantly decrease performance. If you'll be storing much more larger chunks of data in your database, consider moving your data to the disk.
Upvotes: 1
Reputation: 12077
Your insert statement is just inserting a base64 string, not the base64-encoded data. Try passing it through the MySQL FROM_BASE64 function:
$insrtSQL = "INSERT INTO table (s_id, s_name, s_image, s_text, s_link, t_id) VALUES ('a', 'a', FROM_BASE64('$img'), 'a', 'a', 'a')";
This makes the MySQL engine decode the base64 string back into binary data for storage.
Upvotes: 2