PHP - Mysql blob to image
I've read a lot of posts but still doesn't work for some reason. As the title suggests, I want to display an image on a website that is stored in MySQL
as MEDIUM BLOB
. Here's the code that loads 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 that 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 the original image, I get this:
source to share
You base64 encoded it twice: once when you paste it into the database and again when you send it to the browser.
Base64 encoding has a tangible result; that is, it transforms the data. It's not temporary. The data in your database is a base 64 representation of the image bytes, and the same data you pull later with SELECT
.
So, you only want to do the encoding once.
source to share