I am facing an issue to get images from database. I went through so many articles of stack and other websites also, but none have the solution I am looking for. How can I get images stored in the database on the page?
Here is the code, kindly check it and let me know what mistake I made. All help is really appreciated.
<?php
// I have database name databaseimage
// I have a table named store
// I have 3 columns into the table store
// id (int primary key ai), name (varchar), and image (longblob)
// prevent accesing the page directly
if($_SERVER['REQUEST_METHOD'] !='POST') {
echo "you can not acces this page directly";
die();
}
else {
print_r($_FILES);
// file properties
$file = $_FILES['image']['tmp_name'];
echo "<br>$file";
if(!isset($file)){
echo "please select an image";
die();
} else {
//actual image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])) ;
// image name
$image_name = addslashes($_FILES['image']['name']);
echo "<br> image name is = $image_name";
//geting image size to check whether it is actually an image or not
$image_size = getimagesize($_FILES['image']['tmp_name']);
echo "<br>";
print_r($image_size);
if($image_size==FALSE) {
echo "plese select an images only";
die();
}
else {
#code to put an image into the database
// connect to database
try {
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<br>connection succesfull";
// make a query
$extr = $con->prepare("INSERT INTO store (name, image)
VALUES (:na , :im)" );
//$a=1;
//$extr->bindParam(':i', $a);
$extr->bindParam(':na', $image_name);
$extr->bindParam(':im', $image, PDO::PARAM_LOB);
if ( $extr->execute()==true) {
echo "<br>image uploaded succesfully";
# insert is working. I can insert images into database
# but really facing problem while displaying those images
# below is the code I tried
# CODE for to show uploaded files
# to show images which is uploaded
$show = $con->prepare("SELECT * FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_BOUND) ) {
# SHOW IMAGES
//echo "<img src = '$row[image]' alt='image' >";
echo '<img src= "data:image/png;base64,'.base64_encode($row['image']).'"
height="100" width="100" />';
}
} else {
echo "<br>image not uploaded";
}
}
catch(Exception $e)
{
echo "<br> Connection failed: " . $e->getMessage();
}
}
}
// disconnect the connection
$con = null;
}
?>