Ashish Ashish - 6 months ago 19
SQL Question

how to display blob images

i am trying to insert & display multiple blob images but because of some mistake its not appearing to the page and multiple images also not getting saved, the code is as follows:
test1.php[inserting the blob images]:

$conn = mysqli_connect("localhost", "root", "root", "test");

for($i=0; $i<count($_FILES["userfile"]["name"]); $i++){

$imageName = mysqli_real_escape_string($conn, $_FILES["userfile"]["name"]);
$imageData = mysqli_real_escape_string($conn, $_FILES["userfile"]["tmp_name"]);
$imageType = mysqli_real_escape_string($conn, $_FILES["userfile"]["type"]);
$image = file_get_contents($imageData);
$image = base64_encode($image);
if($imageName!=''){

mysqli_query($conn, "INSERT INTO files SET mime = '".$imageName."', data= '".$image."' ");
$result = array("insert_res"=>"110");
echo json_encode($result);

}else{
$result = array("insert_res"=>"111");
echo json_encode($result);
}
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<!-- <form name="" action="<?php echo $_SERVER["PHP_SELF"]; ?>" id="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<input type="submit" name="submit" value="Upload" />-->
<img src="test_dis.php?id=1" />
<!--</form>-->

</body>
</html>


test_disp.php[display images from database]:

$conn = mysqli_connect("localhost", "root", "root", "test");


if(isset($_GET['id'])){
$id = mysqli_real_escape_string($conn, $_GET['id']);

$sql = "SELECT * FROM files WHERE id = '".$id."' ";
$result = mysqli_query($conn, $sql);
While($row = mysqli_fetch_assoc($result)){
$imageData = $row[data];
}
header("contetnt-type: image/jpg");
echo $imageData;
}
else{
echo 'error';
}


for single image its working fine, but when there are multilple images its not inserting all and also not fetching.
i m getting these all images from an IOS App.
how to solve it ?please hlp
while displaying its coming like this.
enter image description here

Answer

You have encoded your original image i.e. base64_encode() so you need to reverse this encoding so it becomes an image again.

test_disp.php

$conn  = mysqli_connect("localhost", "root", "root", "test");

if(isset($_GET['id'])){
    $id = mysqli_real_escape_string($conn, $_GET['id']);

    $sql       = "SELECT * FROM files WHERE id = '$id'";
    $result    = mysqli_query($conn, $sql);
    if ( $result === false ) {
        // check the query actually worked
        echo mysqli_error($conn);
        exit;
    }
    $row       = mysqli_fetch_assoc($result);

    header("content-type: image/jpg");
    echo base64_decode($row[data]);             // < added function

} else {
    echo 'error';
}

You also dont need a while loop when a query will only return on result row!