hi,
i am new to php. I am trying to fetch the image stored in database by using mysqli but couldnt fetch it. Please help me with this. Please find the code and let me know where i am lacking...

<?php 
$link = mysqli_connect('localhost','root','','db_image') or die(mysqli_connect_error());

if(isset($_POST['btn_submit'])){
extract($_POST);

$file_name=$_FILES["image"]["name"];
$file_tmp=$_FILES["image"]["tmp_name"];

$check = getimagesize($_FILES["image"]["tmp_name"]);
print_r($check);

echo'<br>';
if($check !== false){
    $file_name = $_FILES["image"]["name"];
    print_r($file_name);
    echo "<br>";
    $imgContent = addslashes(file_get_contents($file_tmp));
    $query = "insert into insert_image(Image,Image_Name,user_regon) values('$imgContent','$file_name', NOW())";
    if(mysqli_query($link,$query)){
        echo"Image uploaded successfully";  
    }
    else{
        echo"Failed to upload image". mysqli_error($link);; 
    }   
}else{
        echo "Please select an image file to upload.";
    }   
}

if(isset($_POST['btn_display'])){ 
 $query = "select * from insert_image"; 
 $result = mysqli_query($link,$query);
 while($row = mysqli_fetch_assoc($result)){
    extract($row);
    //$imgdata = $row["Image"];
    echo $row[0] . ': ' . $row[1] . ' ' . $row[2];
    //print_r($imgdata);
?>
<table border="1">
<tr>
    <td>ID</td>
    <td><?=$id?></td>
</tr>
<tr>
    <td>Image</td>
    <td><?=$Image?></td>
</tr>    
</table>
<?php   
    echo "User ID". $id;
    echo "<br />";
}
mysqli_close($link);
}

?>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
        Select image to upload:
        <input type="file" name="image"/>
        <input type="submit" name="btn_submit" value="UPLOAD"/>
        <input type="submit" name="btn_display" value="Display"/>
</form>
</body>
</html>

Dani AI

Generated

In the code posted by the main problems are how the binary data is escaped, how the row data is read back, and how the image is output. Using addslashes() on file_get_contents() is not a safe way to store binary blobs; extract($_POST) and storing NOW() into a column called user_regon look like logic/schema mistakes; and printing raw binary (or using numeric indexes with mysqli_fetch_assoc) will produce gibberish or nothing. Use parameterized queries (prepared statements) instead of manual escaping. (php.net)

A straightforward, reliable approach is to use PDO and bind the file stream as a LOB. Example (insert side):

$pdo = new PDO('mysql:host=127.0.0.1;dbname=db_image;charset=utf8mb4','dbuser','dbpass',[
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$stmt = $pdo->prepare("INSERT INTO images (image_name, mime, image, uploaded_at) VALUES (?, ?, ?, NOW())");
$fp = fopen($_FILES['image']['tmp_name'], 'rb');
$stmt->bindParam(1, $_FILES['image']['name']);
$stmt->bindParam(2, $_FILES['image']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$pdo->beginTransaction();
$stmt->execute();
$pdo->commit();

PDO maps LOBs to streams when you use PDO::PARAM_LOB, which avoids manual escaping and works well for large files. (php.net)

For display, either serve the blob through a dedicated script that sends the correct Content-Type header, or embed it as a base64 data URI. Example (serve file):

// image.php?id=123
$stmt = $pdo->prepare("SELECT mime, image FROM images WHERE id = ?");
$stmt->execute([$_GET['id']]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
header('Content-Type: '.$row['mime']);
echo $row['image'];

Pick the DB blob type to match your expected sizes (TINYBLOB / BLOB / MEDIUMBLOB / LONGBLOB). If you only need simple file hosting, storing files on disk and saving paths in the DB is usually simpler and faster. (dev.mysql.com)

Extra tips: check $_FILES['image']['error'], validate with finfo or getimagesize(), limit allowed MIME types and file size, use move_uploaded_file() for filesystem storage, and close streams/transactions. As noted, the low-level mysqli approach uses send_long_data() for very large blobs, but PDO LOB binding or storing file paths will be easier to implement and maintain.

Your method are wrong for BLOBs - read this manual

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.