I am able to retrieve single image from mysql database using php.
Now I want to retrieve multiple images.
Here is the piece of code:
<?php
--db connection code--
$sql = "SELECT image FROM try WHERE status='0'";
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
while ($row = #mysql_fetch_assoc($result))
{
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
echo '<br>';
}
?>
executing this code, only first image in table is being displayed.
How to retrieve multiple images?
You are using Content-type: image/jpeg, which means it can only return one image, as the browser will only expect one. If you want to return multiple images to download you have to do some workaround.
One option would be to first pack the files together into one file (like a ZIP archive), and push that to the user.
Or if you don't want to push this as a download, then create a HTML page, with image links to your images. Each of the link will only return one of course.
You need to pass the loop counter in result_mysql
$count=0;
while ($row = #mysql_fetch_assoc($result))
{
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result,$count);
$count++;
}
Please don't use the error suppressor #
mysql_result
NOTE : Please don't use mysql* functions in your new code they are
depriciated in newer versions use mysqli* or PDO
As the Content-type: image/jpeg returns only a single image, you should consider saving the paths of the images in your database table. Later on you won't have any problems fetching all of them and echoing the source elements in your html.
Related
I am using a PHP script that outputs an image, what I am trying to do is track when the image is opened on an email, The code works to display the image but does not run the database query and update the count.
The PHP code as follows.
$image = $_GET['image'];
require_once('connections/site.php');
mysql_select_db($database_site, $site);
$query_requests = "SELECT count FROM tracker WHERE id = '1'";
$requests = mysql_query($query_requests, $site) or die(mysql_error());
$row_requests = mysql_fetch_assoc($requests);
$count = $row_requests['count'];
$newcount = $count++;
$query_update = "UPDATE count SET count = '$newcount' WHERE id = '1'";
$update = mysql_query($query_update, $site) or die(mysql_error());
header("Content-Type: image/jpeg");
readfile('https://mysite.co.uk/images/'.$image);
Maybe I should be using a different method? I was searching around for a way of tracking a standard image open but I couldn't seem to find a decent method so I thought I would try and cook something up to do this.
The problem is that readfile reads and directly writes to the output buffer, hence if you're going to use that method, you'll need to move the readfile to the end of your script.
However, there are a few other concerns:
Your script is using a deprecated database API functions (mysql_*) - you really need to read How can I prevent SQL injection in PHP?
You're potentially exposing other files as you're not attempting to validate what's being fetched via readfile. For example, if $_GET['image'] contains ../connections/site.php, your script will potentially output raw (i.e.: un-parsed) PHP files containing sensitive database settings, etc.) See the existing Preventing Directory Traversal in PHP but allowing paths question/answer for more information.
You're not outputting Content-Type, or Content-Length headers, etc.
put readfile('https://mysite.co.uk/images/'.$image); at the bottom of your code and add this line just before it:
header("Content-Type: image/jpeg");
I have uploaded an Image in my database. The datatype is BLOB. Now I want to view this image in my browser. I have written the following code but its not generating the image. Kindly check it.
Thanks
<?php
include 'connect.php';
//$id= $_GET['product_id'];
$query_images = "SELECT image FROM product_images WHERE product_id=121";
if (!$query_images_result = mysql_query($query_images))
{
echo mysql_error();
}
else
{
$fetch_images = mysql_fetch_array($query_images_result);
$print_images = $fetch_images['image'];
header('Content-type:image/jpeg');
echo $print_images;
}
?>
File 2
<body>
<img src='single_product_image_show.php' alt="image" />
</body>
maybe something like this? You might wanna use base64 encoding to build in the image
FYI: NOT TESTED.
$sql = "SELECT `image` FROM `product_images` WHERE `product_id`=121 LIMIT 1";
$query_images_result = mysql_query($sql);
if (!$query_images_result)
{
echo mysql_error();
}
else
{
list($print_images) = mysql_fetch_array($query_images_result);
$base64source = "data:image/jpeg;base64," . base64_encode($print_images);
echo '<img src="'.$base64source.'" alt="" />';
}
There are multiple possible reasons why this could happen. First try your script directly without "header('Content-type:image/jpeg');" so you can see what it actually returns. Like http://[youhostname]/single_product_image_show.php I assume you will see some errors.
Some best practices to serve images from php:
If you can remove the end php tag (?>). You don't actually need it and you can avoid issues when you have whitespace character after the close tag which will be written to the response and so results as a corrupt image.
You should specify the Content-Length header as well. It's not mandatory but the browser
will know how big the file it has to download.
Specify some cache control headers (https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) so browsers can cache your image so it won't result a full page load and mysql query every time the image appears on the site.
You can store ETag and/or Last-modified in the database which you can retrieve and put in the headers.
I have a postgres database with stored images 'bytea' type and I try to display them into a browser with PHP. I found the way to display one of them but I can't make it for more than one. The code I use is the following:
File Name - display_image.php
$conn = pg_connect("dbname=test user=postgres password=postgres");
$temp = '/home/postgres/tmp.jpg';
$query = "select lo_export(image, '$temp') from map ";
$result = pg_query($query);
if($result)
{
while ($line = pg_fetch_array($result))
{
$ctobj = $line["image"];
echo "<IMG SRC=show.php> </br>";
}
}
else { echo "File does not exists."; }
pg_close($conn);
File Name - show.php
header("Content-type: image/jpeg");
$jpeg = fopen("/home/postgres/tmp.jpg","r");
$image = fread($jpeg,filesize("/home/postgres/tmp.jpg"));
echo $image;
The problem seems to be the "tmp.jpg" virtual file which displays only one image. If the result of the query is 7 images then it displays 7 times the same image within a while loop. How can I solve this?
Thanks for the interest!
I did this some time ago for bytea.
You need to run your bytea data through pg_unescape_bytea. See http://php.net/manual/en/function.pg-unescape-bytea.php
Basically your SQL query returns the bytea field in an escaped format.
However this is not what you are doing. And so the above is just for the next poor sap who comes here looking for bytea help. Please amend to note you are using LOB's not BYTEA's.
Also note that your code there is not concurrency safe. If two users request different images, my guess is that you will get both users getting different images. For this reason you should add the oid to the retrieval url, and name your file /tmp/$oid.jpg where $oid is the oid of the large object. You will need to retrieve that info (I believe it looks like it is stored in the image field of map?). On the other hand that assumes that all files are essentially public. if that's not the case, you want to move everything into the show_image.php and clean up when you are done.
I've create a table where I've saved images through "BLOB". I need to show those images along with other items. But I don't know how to show those images together in the same page.
Here's my php code that displays other things in form of a table. Similarily, I wanted to display images accordingly. Any help?
<?php
$display_query = mysql_query("SELECT * FROM eportal");
echo "<table id='pageTable'><thead><tr><th>Item code</th><th>Description</th><th>Cost</th></tr></thead>";
echo "<tbody>";
while($row = mysql_fetch_array($display_query)){
print "<tr><td>".$row['itemid']."</td><td>".$row['description']."</td><td>";
print "₹".$row['cost']."</td></tr>";
}
echo "</tbody>";
echo "</table>";
mysql_close($connection);
?>
Saving images to the DB is not a good idea but if You think You need to it this way, then You can retrieve the data from DB table, encode it to base64 (http://php.net/base64_encode) and then in HTML print it in this way:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Using PHP You would write:
echo '<img src="data:'.$image_mime_type.';base64,'.base64_encode($image_data_from_db).'" alt="My image alt" />';
As other people mentioned, storing the images in the database is usually a bad idea.
Images are not transmitted in the same HTTP response with another page data.
To show images from the database, you would need to implement a script which, given the item id, would read the field and send the image's binary data; and provide the path to the script in your form's <img src="">:
while($row = mysql_fetch_array($display_query)){
print "<tr><td>".$row['itemid']."</td><td>".$row['description']."</td><td>";
print "₹".$row['cost']."</td><td>";
print "<img src=\"image.php?id=".$row['id']."\"></td></tr>";
}
image.php is another script which outputs the value of image_blob given the eportal.id. You would also need to provide correct size and mime type in the headers.
You better just store the images in a file (accessible by the web server) and store the path fo the file in the database.
Read the Blob data and write it into the file with header type image.. and try to print it, It should display the image file.
And yes saving image or any file in DB is really a bad habit as you are increasing DB size and it slowdown the performance also.. I suggest you to just try to convert you Blob into Image but don't apply in your work. Just save the image at desired location and keep its location path into DB to fetch and save next time.
The debate of storing blobs versus storing a path to the image file on disk has been debated over and over again. Microsoft provides a research paper comparing the pros and cons of each here. With that said, to display a blob as an image you need to make a call to a separate page and output header information that tells the browser what type of image is stored.
For example:
connectToDatabase();
$sql = "SELECT image_blob FROM eportal;";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: image/jpeg");
echo $row['image_blob'];
$db->close();
In case you still want to save your images in database, you will need second script which will get those images from database and pass them to browser with correct headers.
header("Content-type: image/jpeg");
#
# Replace this with database read:
# readfile('myimage.jpg');
Also, you will need to store what kind of image u use. There will be different header for JPEG, GIF or PNG file.
I'm trying to display multiple images using PHP and MySql database, even if using the while loop I don't get all of the images, I only get one, I mean the first one in the table. What's the problem ?
I'm using a table ID_IMAGE (int, pk, auto increment) and myImage (blob)
$query = mysql_query("SELECT myImage FROM image");
while($data=mysql_fetch_array($query)) {
header('Content-type: image/jpg');
echo $data['myImage'];
}
A possible way to solve this problem is to have a separate script to dynamically output the contents of the image eg. :
image.php
header('Content-type: image/jpg');
// DataBase query and processing here...
echo $data['myImage'];
and call it whenever you need to show images stored in your DB eg. inside your loop:
echo '<img src="image.php?id=' . $data['id'] . '">';
But storing images in the database will take a toll on your server and unless they're really small or you have a good reason to do so, you should only store their physical location on the disk.
You can also use this approach if you wish to hide image location from your users, or control access, but there are better and faster alternatives for that case.
Just to mention the possibility to embed the images directly in html by encoding them, you can use this:
$query = "SELECT myImage FROM image";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="data:image/jpg;base64,' . base64_encode($row['myImage']) . '">';
}
}
Pro:
The browser does not need to load the images over an additional network connection
You can query and display multiple images in one request
Con:
If the image(s) are big and/or there will be many images, the page will be load slow
Encoding an image to base64 will make it about 30% bigger.
For more information about base encode images:
http://davidbcalhoun.com/2011/when-to-base64-encode-images-and-when-not-to/
base64 encoded image size