MySQL Question

PHP - Mysql blob to image

I've read many posts but for some reason it still doesn't work. As in the title, I want to display image in the website which is stored in MySQL as MEDIUM BLOB. Here is the code which uploads the image:

if (isset($_FILES["fileToUpload"]["tmp_name"])) {

if(getimagesize($_FILES["fileToUpload"]["tmp_name"]) == FALSE){
echo '<p style="color: red" >No file selected</p>';
}
else{
echo '<p style="color: red" >SELCETED</p>';
$image= addslashes($_FILES["fileToUpload"]['tmp_name']);
//$imageName= addcslashes($_FILES["fileToUpload"]['name']);
$image = file_get_contents($image);
$image = base64_encode($image);

}
}


if (isset($_POST['trescText']) )
$trescText=$_POST['trescText'];

if($titleText != ""&& $trescText != ""){

$stmt = $conn->prepare("INSERT INTO blog (title,cykl,tresc, image) VALUES('$titleText','$cyklText','$trescText','$image')");
$stmt->execute();
header('Location: addPost.php');
}

$conn->close();


And the code which displays it:

<?php
$stmt = $conn->prepare("SELECT image FROM blog WHERE id='98'");
$stmt->execute();
$stmt->bind_result($image);

while ($stmt->fetch()) {

// echo '<img src="data:image;base64,'$image' "/>';


echo '<img src="data:image/jpeg;base64,'.base64_encode($image) .'" />';
}

?>


The problem is that instead of orginal image I get this:

enter image description here

Answer Source

You base64-encoded it twice: once when inserting it into the database, and again when sending it to the browser.

Base64-encoding has a tangible result; that is, it transforms the data. It is not temporary. The data in your database are the base-64 representation of your image's bytes, and that's the same data that you pull out later with SELECT.

So you only want to do the encoding once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download