PHP: Retrieve image from MySQL using PDO - php

I am refactoring some old code, including rewriting basic mysql queries to use PDO.
The following works brilliantly in all browsers and for all image types:
$query = 'SELECT image FROM image WHERE imageid=' . $image_id;
$result = mysql_query($query, $db_conn); querycheck($result);
header("Content-type: image");
echo mysql_result($result, 0);
Unfortunately, however I rewrite it using PDO, it doesn't work. I've been through the entire PDO documentation and the standard web search, but none of the advice/solutions work.
How can one easily fetch and image from MySQL using PDO and display it?
Edit 1:
Matthew Ratzloff gives what should be the obvious answer below, but it does not work.
Here is the actual code that I test using PDO (and I have tried many variants/parameters):
$connectstring_temp = 'mysql:host=' . $A . ';dbname=' .$B;
$dbh_temp = new PDO($connectstring_temp, $login, $password);
#$dbh_temp->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#$dbh_temp->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
$sql = "SELECT image FROM image WHERE imageid=" . $image_id;
$query = $dbh_temp->prepare($sql);
$query->execute();
$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;
I've kept the same syntax, although for the final code $image_id needs to be passed as a parameter. The code above does NOT work. PDO works fine for all other queries of all types.

You need to paramaterize the imageid value and bind the parameter to PDO::PARAM_LOB:
$sql = "SELECT image FROM image WHERE imageid=:id";
$query = $db_conn->prepare($sql);
$query->execute(array(':id' => $image_id));
$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;
Of course, you'll also want to specify the complete, correct content type (e.g., image/png).

My personal approach to Image Blobs is using a php file to serve the image, in combination with a GET argument... It's 100% effective and it doesn't involve file creation... For instance, the file to serve the image from the blob would be:
image.php:
<?php
$db = new PDO('mysql:host=localhost;dbname=anything; charset=utf8', 'account','password');
if (isset($_GET['imageid'])) {
$result = $db->prepare("SELECT image FROM image where imageid = ?");
if ($result->execute(array($_GET['imageid']))) {
$row=$result->fetch();
echo $row['pic']; //this prints the image data, transforming the image.php to an image
}
} // you can put an "else" here to do something on error...
?>
This can be called from you main script... For instance:
<?php
$db = new PDO('mysql:host=localhost;dbname=anything; charset=utf8', 'account','password');
//... some code to do your job, where you get your imageid from
$imageid=...
?>
<img src="./image.php?imageid=<?php echo $imageid;?>">

You can use this code to get image from database using PDO:
public function getImage($id){
$sql = "SELECT * FROM images WHERE id = ?";
$sth = $this->dbh->prepare($sql);
$sth->bindParam(1,$id);
$sth->execute();
$num = $sth->rowCount();
if( $num ){
$row = $sth->fetch(PDO::FETCH_ASSOC);
header("Content-type: ".$row['type']);
print $row['image'];
exit;
}else{
return null;
}
}
type - data type(column name) such as image/png or image/gif
image - image data(column name) stored in table as LOB
$this->dbh connection handler
It works for me but now I need to find out how to use it with JS because result of this function is passed to JavaScript code - so called ajax

This code displays all the images in the dabase so you can change it and make it do what you want it to do
getMessage();
}
?>
<?php
#the folder where the images are saved
$target = "image_uploads/";
$image_name = (isset($_POST['image_name']));
$query = ("SELECT user_id ,image_name FROM tish_images");
$image_show= $con-> prepare($query);
$image_show->execute();
while($record =$image_show->fetch(PDO::FETCH_ASSOC)) {
#this is the Tannery operator to replace a pic when an id do not have one
$photo = ($record['image_name']== null)? "me.png":$record['image_name'];
#display image
echo '<img src="'.$target.$photo.'">';
echo $record['user_id'];
}
?>

Related

Retrieve image long raw datatype stored in oracle database in php

I tried to display image stored in oracle database
I get it as decode data
I tried to this code but not work
first way
$img= studimage::select('studimage')->where('studnum',$id)->first();
header("Content-type: image/jpeg");
echo ($img->studimage) ;
sec-way
echo '<img src="data:image/jpg;base64,'. base64_encode($img->studimage). '" />';
the two ways does not work :(
I'm using this same functionality in one of my project, please check my code below
you can either make a page that will render the image
<img src="image.php?id=123" />
That image.php page would have this:
$sql = "SELECT image FROM images WHERE image_id = " . (int) $_GET['id'];
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
if (!$row) {
header('Status: 404 Not Found');
} else {
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
}
Or, you could base64 encode it into the src (note, not all browsers handle this well):
<img src="data:image/jpeg;base64,<?php echo base64_encode($img); ?>" />

Image from blob object not displayed in a page

This is my HTML code for displaying image stored as blob object which is stored in a database.
<tr><td>photo</td><td><img src="image.php?id=<?php echo $employee['id']; ?>" /></td></tr>
This is the image.php file:
<?php
include db.php;
$employee_id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? intval($_GET['id']) : 0;
try
{
$sql = "SELECT photo
FROM employee where id = $employee_id limit 1";
$s = $pdo->prepare($sql);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Employee not found' . $e->getMessage();
include 'error.html.php';
exit();
}
$employee = $s->fetch();
$image = $employee['photo'];
header('Content-Type: image/jpeg');
echo $image;
?>
When I look at the HTML code in Firebug, I can see
<img src="image.php?id=9">
But no image is displayed in the table row. Do you know how to find out what is wrong?
When I open the page ...image.php?id=9 in Firefox
It shows a message
The image ...image.php?id=9 cannot be
displayed because it contains errors.
It is strange that every image I have contains an error. I inserted only images with
size smaller than the blob object.
do you get an error?
try to use "exit;" after the echo and remove the closing php tag.
it's optional and you don't really need it (http://php.net/manual/en/language.basic-syntax.instruction-separation.php).
header('Content-Type: image/jpeg');
echo $image;
exit;

Unable to get the image from mysql DB

I'm new to php. I have a sample mysql db in that I have a table named testdb with columns id(INT) and image(BLOB). I have uploaded an image into testdb. Uploaded successfully. The following is the php code. The variable $conn contains the connection details. I have a html page which redirects to this php page on submitting.
<?php
$name = $_FILES["sample"]["name"];
echo $name . "<br/>";
$tmp_name = $_FILES["sample"]["tmp_name"];
echo $tmp_name . "<br/>";
$size = $_FILES["sample"]["size"];
echo $size . "<br/>";
$contents = file_get_contents($tmp_name);
$htmlen = htmlentities($contents);
$cont = mysql_real_escape_string($contents);
$query = "INSERT INTO testdb(image)
VALUES ('$cont')";
$dbquery = mysql_query($query, $conn);
if($dbquery){
echo "successfully inserted";
}
else{
echo "could not inserted" . mysql_error();
}
?>
I am trying to get the image with the following code. But it is showing string characters rather than the image. As far as I know this should work fine.
<?php
$query = "SELECT image, id
FROM testdb ";
$dbquery=mysql_query($query , $conn);
if(! $dbquery){
echo "Could not selected the data from database. " . mysql_error();
}
while( $row = mysql_fetch_array($dbquery) ){
$decodeimg = html_entity_decode($row["image"]);
echo "<img src= $decodeimg/><br/> hellow orld <br/>";
}
?>
Could anyone help me with this. Thanks in advance.
Instead of storing the actual image in your database (which is redundant because it is probably stored on your server too); why don't you just store the PATH to the image as a string, query the string from your db and then append it to the 'src' attribute with php.
I am also got the same error when show the BLOB image from DB. I just use the decoding method for this problem....
$photo=$myrow['image'];
echo '<img src="data:image/jpeg;base64,' . base64_encode( $photo ) . '" width="150" height="150" />

images from database via php can't display

thank's for help. I have problem displaying images retrieving from my database.
I cant see the image when loading image.php in img src or directly from the page. When i display the variable without header('Content-type: image/jpeg'); i can see all the code inside, as i put this line all goes off.
I have a table called TABLE with id, title, img stored as longblob directly uploaded inside phpmyadmin.
Can anyone help me?
index.php
<?php
session_start();
include "admin/include/connection2.php";
$data = new MysqlClass();
$data->connect();
$query_img ="SELECT * FROM table ORDER BY data ASC LIMIT 4";
$post_sql = $data->query($query_img);
if(mysql_num_rows($post_sql) > 0){
while($post_obj = $data->estrai($post_sql)){
$id = $post_obj->id;
$titolo = stripslashes($post_obj->title);
$data_articolo = $post_obj->data;
$immagine = $post_obj->img;
// visualizzazione dei dati
echo "<h2>".$titolo."</h2>";
echo "Autore <b>". $autore . "</b>";
echo "<br />";
echo '<'.'img src="image.php?id='.$post_sql['id'].'">';
echo $id;
echo "<hr>";
}
}else{
echo "no post aviable.";
}
// here is the image.php code
<?php
include "admin/include/connection2.php";
$data = new MysqlClass();
// connect
$data->connetti();
$id = $_GET['id'];
echo $id;
$query = mysql_query("SELECT * FROM articoli_news WHERE id='".$id."'"; //even tried to send id='1' but not working
echo $query;
$row = mysql_fetch_array($query);
echo $row['id']; //correct displaying
$content = base64_decode($query['img']);
header('Content-type: image/jpeg');
echo $content;
?>
Delete all "echo" commands except "echo $content;" because there are also appear in the output, and damage your image.
And use ob_start(); in the begining of the script, and check out your script file not contain any of whitespace characters before or after the php begint and close tags .

View image in the image field of the php

Good day!
Could anyone help me, there is a system where users do register via their desktop in a database hosted on the web, we are now developing the web interface of this system, then it has a certain functionality in the system where I have to display the photo user.
I do what normal SELECT in SQL Server, but upon the imagejpeg ($ img); it does not show the whole picture, just a piece of the picture. Could anyone help me? I'm looking for some tutorials on the web and they speak it is because of the size of the field. If the field is of type (image) and the return is in hexadecimal.
Below I tried to do a function with the help of a friend, but she also did not work:
<php
$id = (int)$_GET['id'];
$qryimg = mssql_query(gimage SELECT FROM user WHERE id = {$ id});
$resimg = mssql_fetch_array($qryimg);
$im1 = $resimg['gimage'];
header("Content-type: image/jpg");
$image='';
for($i=2; $i<strlen($im1); $i+=2)
{
$hex = $im1{$i} . $im1{($i + 1)};
$cod = hexdec( $hex );
$image .= chr( $cod );
}
echo $image;
#echo imagejpeg($image);
?>
Why doesn't the following code work? Can't you just echo the image.
<php
$id = (int)$_GET['id'];
$qryimg = mssql_query(gimage SELECT FROM user WHERE id = {$ id});
$resimg = mssql_fetch_array($qryimg);
$im1 = $resimg['gimage'];
header("Content-type: image/jpg");
print $im1;
exit;
What field type is gimage?

Categories