Retrieve Blob image from sql with php

  mysql, mysqli, php, sql

I am trying to retrieve a blob image from sql.
The upload seems to work but when I try to retrieve and display it nothing appears except the logo when Image can’t be load.

The Blob is stock as LongBlob in the sql table.

The way i send it:

if (!empty($_FILES["photo"]["name"])) {
    $fileName = basename($_FILES["photo"]["name"]);
    $fileType = pathinfo($fileName, PATHINFO_EXTENSION);
    $allowTypes = array("jpg", "png", "jpeg", "gif");
    if (in_array($fileType, $allowTypes)) {
        $photo = $_FILES['photo']['tmp_name'];
        $photoContent = addslashes(file_get_contents($photo));
    } else {
        $photo_err = "Please enter a valid file.";
    }
}

then

    $sql = "INSERT INTO post (photo, userId, username, caption, date) VALUES (?, ?, ?, ?, ?)";

    if ($stmt = mysqli_prepare($con, $sql)) {
        mysqli_stmt_bind_param($stmt, "bisss", $paramPhoto, $paramUserId, $paramUsername, $paramDescription, $paramDate);
        $paramPhoto = $photoContent;
        mysqli_stmt_send_long_data($stmt, 0, $photoContent);
        $paramUsername = $_SESSION["username"];
        $paramDescription = $description;
        $paramDate = date('Y-m-d h:m:s');
        $userId = $_SESSION["id"];
        $paramUserId = $userId;

        if (mysqli_stmt_execute($stmt)) {
            $redirect = "location: ../index.php";
            header($redirect);
        } 

When i look to phpmyadmin, the blob is in the table and filled.

Finally to retrieve/display it:

$sql = "SELECT * FROM post";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$db = new mysqli("localhost", "root", "*******", "testDb");
while ($row = mysqli_fetch_assoc($result)) {
    $photo = base64_encode($row["photo"]);
    echo "<img class='image' width='500px' src='data:image/jpg;charset=utf8;base64, $photo />";
}

Source: Ask PHP

LEAVE A COMMENT