-2

I try to display an image from mysql database into my php website But the image did not display, only the image description display. Please help why is my code did not display the image correctly. Below is the script that i use to save the image into database with blob data type.

*<?php
    $image = $_POST['images']['tmp_name'];

    $sql = mysql_query("INSERT INTO product(image) VALUES('$image')");
    if($sql){
    echo "Product Registration Successful";
    }
    else{
         echo "Product Registration Failed";
         }
?>*

Below is the script that i use to display the image into the website:

  *<?php

    $sql = mysql_query("SELECT * FROM product");
    while ($tampil = mysql_fetch_array($sql)) {
    ?>
    <tr>

        <td class="img-thumbnail"><?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $tampil['image'] ).'"/>'; ?></td>
</tr>
 <?php  
}
?>*
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Abeth
  • 1
  • 2

2 Answers2

3

You are not saving the image content to the database in your PHP, you are only saving the temporary name.

You can solve this using this code:

<?php
$image = file_get_contents($_FILES['images']['tmp_name']);
$image = base64_encode($image);

$sql = mysql_query("INSERT INTO product(image) VALUES('".$image."')");
if ($sql) {
    echo "Product Registration Successful";
} else {
    echo "Product Registration Failed";
}
?>
Jacob
  • 2,769
  • 3
  • 21
  • 29
2

Solution with: move_uploaded_file()

$image['name']['tmp_name'] is a temporary location, to store things that are deleted after a while, to actually, store the image you have to use move_uploaded_file() to another folder. This should be done after validating the image.

Solution for: Base64_incode()

IF you want to only use the base64 value, the you have to store the image information as such in the database, in this case you don't need to move the file

$image = imagecreatefromstring($file);
ob_start();
imagepng($image);
$contents =  ob_get_contents();
ob_end_clean();

Now, store $contents in your database.

samayo
  • 16,163
  • 12
  • 91
  • 106