I have two separate files, one is to display the html/php document image, and the other is a php file that renders the image using the header function content-type:image/jpeg.
I tried using it with one image and it works well. However, I need to display multiple images. How could I do this?
The html/php doc has an img tag that points out to the php file that renders the image
echo "<image src=Image.php>";
The image.php
$selectimage = mysql_query("SELECT Image from ImageTbl", $con);
if($selectimage)
{
header("Content-type:image/jpeg");
while($row = mysql_fetch_array($selectimage))
{
echo $row["Image"];
}
}
make two files one for image another for fetching the row like this
image.php
$image_id = $_GET["id"];
header("Content-type:image/jpeg");
//query database to get only one image from id
echo $row["Image"];
another file
getimages.php
//query for image data
while($row = mysql_fetch_array())
{
echo "<img src='image.php?id=$row[id]' />";
}
You can't output all the images together, because to the browser, it will look like the data of multiple images mushed together, which is nonsensical. Also, each image tag can only display one image. To solve this, give the image table an ID field to identify the image.
Then in the file that outputs HTML, do something like this (passing the ID for the image you need):
echo "<image src='Image.php?id=1>";
echo "<image src='Image.php?id=2>";
echo "<image src='Image.php?id=3>";
And then in the file that outputs the image, do:
$id = intval($_REQUEST['id']); // intval will validate the ID to be an int
$selectimage = mysql_query("SELECT Image from ImageTbl WHERE id=$id LIMIT 1", $con);
if ($selectimage) {
$row = mysql_fetch_array($selectimage);
if ($row) { // check if the image really exists
header("Content-type:image/jpeg");
echo $row["Image"];
}
}
Use a foreach loop to loop through the requested records and echo them out independently to the img tags which your using.
That would be the best way in my opinion.
If you want to display number of different images using one script, try to add some unique hash to the script name ( for e.g. md5( microtime() ) )
$seed = md5( microtime() );
echo '<image src="Image.php' . $seed . '">';
Related
My program needs to upload images, so an image (varchar) location is saved in a MySQL database. It's working so far.
Now I want to display images and this does not work. Here is the code:
include ('connect.php');
if(isset($_POST['submit'])){
$filetemp= $_FILES['image'] ['tmp_name'];
$filename= $_FILES['image'] ['name'];
$filepath= "images/".$filename;
move_uploaded_file($filetemp,$filepath);
$sql=mysqli_query($con,"insert into images (image) value ('$filepath')");
if($sql){
echo "uploaded";
}
else{
echo " not uploaded";
}
}
$sql=mysqli_query($con,"select * from images");
while($row=mysqli_fetch_array($sql)){
echo "<img src=' images/".$row['image']."'>"; // the problem is here, its just displaying img icon, not actual image
}
?>
remove images from image path, you already store this in image column in images table
echo "<img src='/".$row['image']."'>"; // the problem is here, its just displaying img icon, not actual image
Correction :
$sql=mysqli_query($con,"select * from images");
while($row=mysqli_fetch_array($sql)){
echo "<img src='".$row['image']."'>"; // the problem is here, its just displaying img icon, not actual image
}
Also you need to get the actual path via __FILE__ in case if needed.
You are adding images/ into the database then when you call the row to display the image you're adding images/ adding making it look in images/images/filename
I'm accessing an API which is returning the value of an array. I want a image to be displayed based on the result. For example if the div contains "above average" then display an image called aboveAverage.png.
echo $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'];
This results is "Above Average" How can I display a particular image to correspond to this?
Something like ->
if Div "crime_level" = above average then:
display aboveAverage.png
I'm pretty new to PHP, sorry i'm a noob.
Use a case selecting switch
switch ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']) {
case "Above Average":
$image = "aboveAverage.png";
break;
case "Below Average":
$image = "belowAverage.png";
break;
default:
$image = "unknown.png";
};
echo "<img src=\"$image\" />";
Doing it this way allows you to remove your logic from your display by setting the variable as $image so you're not having to update 20 different potential image tags. It also allows you to cater for many different cases of the string without ending up lost in if then else hell
If the values of
$cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']
are finite and you happen to know them all you could use an associative array, where the key would be the value returned by the API and the corresponding value to that key would be the file name of the image you want to display. Something like:
$images = array(
'Above Average' => 'aboveAverage.png',
'Below Average' => 'belowAverage.png',
// etc
);
$img = 'default.png'; // set a default image file
$crimeRate = $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'];
if (array_key_exists($crimeRate, $images)) {
$img = $images[$crimeRate];
}
// output the image
echo "<img src=" . $img . " />";
There are two parts to your question. The first is how to compare the array element to a string. This is accomplished like this:
if ( $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'] == "Above average" ) {
// The second part of your question is how to display an image.
echo '<img src="aboveAverage.php" />;
}
There are other ways to display images via PHP scripts, such as setting an appropriate header and dumping the image content directly. If you are looking for such a solution, see Output an Image in PHP.
Here is some approach:
$toDisplay = array("Above average", "Average") ;
if (in_array($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'], $toDisplay)){
echo "<img src='image.png' alt='image'/>" ;
}
A simple if and echo will do:
if ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'] == "above average") {
echo "<img src='aboveAverage.png' />
}
I have been working on a project but I have reached a point where I am stuck. I have a database that contains the the working status of some mahcines. The values for the status go from 1-5. I need to be able to display a different image for each machine in a webpage based off of the value that appears in the database for that Mahcine. I am drawing a big blank on how to do this. Im using a MySQL DB and everything is written in PHP.
Basically it this. If a machine has a status value of 1 then it shows a green image. If the value is 2 then it would be yellow and so on. . .
Hope you guys can help
You can try something like this:
// your mysql select, wich contains the machine data.
$query = mysql_query("select the data about machines...");
// you iterate on the result set and fetch each row to $data
while($data = mysql_fetch_array($query))
{
switch($data['machine'])
{
case "machine type 1": // you can put integer values here as well, like case 1:
echo '<img src="first_machine.jpg" alt = "first machine" />'
break;
case "machine type 2":
echo '<img src="second_machine.jpg" alt = "second machine" />'
break;
default: // undefinied
echo '<img src = "undefinied.jpg" alt = "undefinied" />'
}
}
Don't use the img tag, instead create a div for which you apply a style class same as the machine status value
<div class="machine status<?php echo $status;?>" ></div>
now in your css,
.status1{
background-image:url(red.jpg);
}
.status2{
background-image:url(green.jpg);
}
.status3{
background-image:url(jpg.jpg);
}
.machine{
width:50px;
height:50px;
}
Ok you can't display multiple images within a image/jpeg page...
You're telling the browser that the page is image/jpeg (in other words, the page is AN IMAGE) but you're echoing out multiple image data
You should rather use the gallery page to show all images like this:
<?php
// $images = result from database of all image rows
foreach ($images as $img) echo '<img src="img.php?id='.$img["id"].'">';
?>
and in img.php:
// Load the image data for id in $_GET['id'];
header("Content-type: image/jpeg");
echo $data;
I create a component in my joomla website. the component shows some photos (not big, only 8KB). the photos are stored in mysql blob. i can upload the photos to the joomla database but i cannot display it on the website. whatever i do it only show some encoding character or blank. I tried to create a separate page but but the result is same. Here is what i have done :
mycomp is my joomla component.
admin.mycomp.php
<?php
function showDetail($option)
{
$db = &JFactory::getDBO();
$id = mysql_real_escape_string(JRequest::getVar('id'));
$query = "select id,myphoto from jos_myphotos where id = ".$id;
$db->setQuery($query);
$rows = $db->loadObjectList();
HTML_myphoto::showPhoto($rows,$option);
}
?>
admin.mycomp.html.php
<?php
class HTML_myphoto
{
...
function showPhoto($row,$option)
{
...
header("Content-type: image/jpeg");
echo $row->myphoto; //this will show some encoding character
echo base64_decode($row->myphoto); //this will show blank page
//change echo with print get the same result.
...
}
...
}
I tried to create a separate page like this :
admin.mycomp.html.php
<?php
class HTML_myphoto
{
...
function showPhoto($row,$option)
{
...
?>
<img src="show_image.php?myphoto=<?php echo $row->myphoto;?>" width=200 height=300>
<?php
...
}
...
}
show_image.php
<?php
$myphoto = (isset($_GET['myphoto'])) $_GET['myphoto'] : false;
if($myphoto)
{
header("Content-type: image/jpeg");
echo $myphoto; //this will show some encoding character
echo base64_decode($myphoto); //this will show blank page
//change echo with print get the same result.
}
?>
the result is same.
I think you have 2 options:
Either you make an image tag with its source in a PHP file receiving only a ID parameter and retrieving the photo's string in the DB and echoing it.
Or you echo directly your photo's string in your tag:
<img src="<?php echo base64_decode($myphoto); ?>" />
EDIT
I just checked in an old app where I store the favicons in a DB. You don't need to base64_decode when you display your image inline (my option 2).
So FYI, this image works:
<img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAACkElEQVQ4y42TTWyUZRSFn/e+n6W00E4l9ScSCZGODXFLIIZENyZu1ITEGBdE3ejGVQksunDlwoUrE0ICCQuomZAYF4YNNvEPlFpjiJRgKq10HDKdmVJxEOh0vu+9h0UrMSyAk9zVOffczXPRI8hdciVNTZ/X6MjLOnrkK3XTLbk64lEK5FIhaf87HyqznYKy5qsLyuUPL/D1OXzkC8U4IhhViC9o7OAnSkkKksQDVG81GR//iAvTbS7OXIQQ1p0Oc3O/YlCAAAcSQIHIEc43Z8/z6r5xfrsiBp9+ArK4FgprNye//oEMDIJDMBDU6jc4d/YXzpz5kcuzC5SGBvBkoMT257ah5FTn/4Qgpqd+InM3LEDr+j8cO/45pyrnmLk0w0uv7KV/cIDCI4GIhUAgY3h4C9W5Kma9LF//l2xpqc33301xcuJLTp+ehLiJbSNlcpxoEanAolF4okB0lRAiuVOt1cje/+AAly8tcHWhDnEDeAfXKo/FTbg7ZLdwCrDI0PAAK7fvQATkYIbN/l4jWh8pAb4BrJ/abI32301MXULKoIhE9bKxt8RKJ4D1gXpIitj+d19j6PGN7CiXQavgHYir3G5fY+tT/Wx/cgulnh6su0JYvUPodiHvAGJz32YoJC222qo1lvTH1b906NBngq06cPBjFZKkXIuNmhZbN3RlvqUTlUnt2fumsGc0NvapkJLcpeRrzF+r31R5dLd2PP+i6s3if//gcndJUqPRUKVSUbPZFCnlkpJcSWmd+dffeE/BntWJk9/eW7q/RJJSSjIzQxKBhIUcgN17dhFCxsREheXlZSStZUIghEBRFACYGRlwz3Q5FuDtt/Yx/fMFSqVB8jwnrPP/Xy7LMtwdM+Mu+2gfA7SP0igAAAAASUVORK5CYII=" style="margin-right: 5px; vertical-align: middle;" class="bbns_itemDragger">
And it is stored in my DB like this (base64 encoded):
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAACkElEQVQ4y42TTWyUZRSFn/e+n6W00E4l9ScSCZGODXFLIIZENyZu1ITEGBdE3ejGVQksunDlwoUrE0ICCQuomZAYF4YNNvEPlFpjiJRgKq10HDKdmVJxEOh0vu+9h0UrMSyAk9zVOffczXPRI8hdciVNTZ/X6MjLOnrkK3XTLbk64lEK5FIhaf87HyqznYKy5qsLyuUPL/D1OXzkC8U4IhhViC9o7OAnSkkKksQDVG81GR//iAvTbS7OXIQQ1p0Oc3O/YlCAAAcSQIHIEc43Z8/z6r5xfrsiBp9+ArK4FgprNye//oEMDIJDMBDU6jc4d/YXzpz5kcuzC5SGBvBkoMT257ah5FTn/4Qgpqd+InM3LEDr+j8cO/45pyrnmLk0w0uv7KV/cIDCI4GIhUAgY3h4C9W5Kma9LF//l2xpqc33301xcuJLTp+ehLiJbSNlcpxoEanAolF4okB0lRAiuVOt1cje/+AAly8tcHWhDnEDeAfXKo/FTbg7ZLdwCrDI0PAAK7fvQATkYIbN/l4jWh8pAb4BrJ/abI32301MXULKoIhE9bKxt8RKJ4D1gXpIitj+d19j6PGN7CiXQavgHYir3G5fY+tT/Wx/cgulnh6su0JYvUPodiHvAGJz32YoJC222qo1lvTH1b906NBngq06cPBjFZKkXIuNmhZbN3RlvqUTlUnt2fumsGc0NvapkJLcpeRrzF+r31R5dLd2PP+i6s3if//gcndJUqPRUKVSUbPZFCnlkpJcSWmd+dffeE/BntWJk9/eW7q/RJJSSjIzQxKBhIUcgN17dhFCxsREheXlZSStZUIghEBRFACYGRlwz3Q5FuDtt/Yx/fMFSqVB8jwnrPP/Xy7LMtwdM+Mu+2gfA7SP0igAAAAASUVORK5CYII=
I'm sorry, did you skip some lines from show_image.php?!
Cause $myphoto is just the id of the photo. You can't base64_decode an ID.
I was wondering for some time, and searching the nets, for an efficient way of displaying an image dynamically using PHP, depending on the result of a query. Per example, there is a field called "devicetype" in my asset table, and I would like to display a different icon depending on the type of device.
Anyone could point me in the right direction? I've been reading around and many articles recommend against inserting images into the DB.
Thanks!
You don't need to insert the images into the DB. Just check the value of the column in your table and then use the appropriate image source based on it. Something like this:
while( $row = mysql_fetch_assoc($result) ) {
$src = '';
switch( $row['devicetype'] ) {
case 'device1':
$src = 'img_for_device.jpg';
break;
case 'device2':
$src = 'img_for_device2.jpg';
break;
default:
$src = 'default.jpg';
}
?><img src="<?php echo $src; ?>" /><?php
}
I would store image in your website folder i.e. "website/deviceimg/*". Then, depending on your sql statement, I would load corresponding image by its name. For example, you might use devicetypes as image names. Loading image is fairly easy:
"< img src=' + devicetype + '.jpg' />"
I'm not sure I fully understand your question but can't you upload all the images you're going to use on your server? I think that's better than storing the actual images in your DB.
So your code will be something like this:
if (results[devicetype] == "A") {
echo '<img src="images/A.png" />'
else if (results[devicetype] == "B") {
echo '<img src="images/B.png" />'
You can insert a link to the image file in the DB.