0

I've uploaded an image and text directly to my table through phpMyAdmin. However when it comes to displaying, the images are showing up as junk text. What could be the issue? The image is a relatively small jpg file. Here is the code:

<?php
    require_once 'login.php';
    $conn = new mysqli($hn, $un, $pw, $db);
    if($conn->connect_error) die($conn->connect_error);
    $query = "SELECT * from classics";
    $result = $conn->query($query);
    if(!$result) die($conn->error);

    $rows = $result->num_rows;

    for($j=0; $j < $rows; $j++) {
         $result->data_seek($j);
         $row=$result->fetch_array(MYSQLI_ASSOC);
         echo 'Cover:' .$row['sleeve'] .'<br>'; 
    }

    $result->close();
    $conn->close();
?>
LuckyStarr
  • 1,458
  • 2
  • 25
  • 38
Agni Scribe
  • 242
  • 3
  • 17

2 Answers2

2

You are doing it the wrong way. Don't save images in database as it is not a good practice. Just save the uploaded image in a directory and save the path to that image in database. It would save you some database space and search time.

Here is some sample code

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

Refer to http://www.w3schools.com/php/php_file_upload.asp for help

Noor Ahmed
  • 1,447
  • 8
  • 14
  • @ noor: but given that the image is now already in the database, why should it display as junk; my problem is with the display. – Agni Scribe Jan 05 '16 at 10:22
  • 1
    http://stackoverflow.com/questions/20556773/php-display-image-blob-from-mysql because it isn't encoded correctly. – Insomnophobia Jan 05 '16 at 10:24
  • thanks, ok, so then if I uploaded it the right way, will it display the right way with the original code i used? am also trying it out... – Agni Scribe Jan 05 '16 at 10:35
  • 2
    @AgniScribe yes ... you have to just place an `` tag and in `src` attribute of `` tag you have to place the path you stored in database. thats it – Noor Ahmed Jan 05 '16 at 10:42
  • 1
    @AgniScribe study this article too before implementing it .http://www.htmlgoodies.com/beyond/php/article.php/3877766/Web-Developer-How-To-Upload-Images-Using-PHP.htm – Noor Ahmed Jan 05 '16 at 10:43
2

Something like this as your echo statement "should" work with your current implementation.

//echo 'Cover:' .$row['sleeve'] .'<br>'; 
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['sleeve'] ).'"/>';

However @Noor is correct, storing images like this is not very efficient.

Insomnophobia
  • 523
  • 4
  • 13