0

This is the structure of my mysql table crij_personne :

  • id
  • photo longblob
  • image_name varchar(64)

My html code is the following:

<input type="file" name="photo" />

The code for uploading the image to my database:

$imagetmp=addslashes (file_get_contents($_FILES['photo'] ['tmp_name']));
$image_name = addslashes($_FILES['photo']['image_name']);
$imagetmp= base64_encode($imagetmp);
$sql = "INSERT INTO crij_personne (description, photo, image_name) VALUES ('".$_POST['description']."','$imagetmp',' $image_name');"; 
if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
} else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }

The code for displaying the image on a web page is:

echo '<img height="300" width="300" src="data:image;base64, '.$row['photo'].'">';

But nothing is happening... I'm doing something wrong, obviously. Thanks for the help.

nad
  • 5
  • 4
  • why you are using base64_encode ? –  Mar 04 '17 at 12:18
  • Take at look at this documentation, http://stackoverflow.com/questions/7793009/how-to-retrieve-images-from-mysql-database-and-display-in-an-html-tag –  Mar 04 '17 at 12:21

1 Answers1

0

Try this one.

For insertion values into the database.

$image_name = addslashes($_FILES['photo']['image_name']);
$sql = "INSERT INTO crij_personne (description, photo, image_name) VALUES ('".$_POST['description']."','$imagetmp',' $image_name');";

if (mysqli_query($conn, $sql)) echo "New record created successfully";
else echo "Error: " .  mysqli_error($conn);

For retrieval of image from Database

$connectDb = mysqli_connect("localhost","root","password","DatabaesName"); //You need to replace with your own credentials 
$query= "SELECT * FROM crij_personne WHERE id = $id";
$sth = $connectDb ->query($query);
$mysqli_fetch_array=mysqli_fetch_array($sth);
header("Content-type: image/jpeg");
echo '<img src="data:image/jpeg;base64,'.base64_encode( $mysqli_fetch_array['image_name'] ).'"/>';

And then retrieve, I hope you will get the correct output.

  • Thanks for the quick answer. But what is "$db"? – nad Mar 04 '17 at 12:45
  • @nad now black background is appearing due to the header funcation. Now, when you will echo right database field, then for sure you image will be on screen. –  Mar 05 '17 at 11:29