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.
Related
I'm making my project and I have something that I don't understand. I want to make an if/else statement or anything that if all the document was uploaded in the database and no one missing it will have a check icon but if there were missing or no upload documents in the database it will have an x icon. The picture or link below is my database. The below code is the data I want to complete.
$vsoi = $row['soi'];
$vciv = $row['civ'];
$vpromo = $row['promo'];
$vassign = $row['assign'];
$vawards = $row['awards'];
$venlist = $row['enlist'];
$vlongpay = $row['longpay'];
$vfamily = $row['family'];
$vsaln = $row['saln'];
$vepem = $row['epem'];
This is the result I want to make.
If documents are complete.
and if not complete.
Thank you in advance!!!
I am not sure is this the solution that you are asking. Because you didn't post more information and the database structure. So I will post the answer as per my assumptions to give you an idea. I see in your database there are documents/ and also documents/CPLATEC.docx. So I assume documents/ as NOT UPLOADED and documents/CPLATEC.docx as UPLOADED and also the field type as VARCHAR. So based on that here is the answer,
I see a series of documents in the whole table but I will only get this soi as for the example.
<?php
$vsoi = $row['soi'];
$imageSrc = '';
if ($vsoi == 'documents/') {
$imageSrc = 'img_for_uploaded.png';
} else {
$imageSrc = 'img_for_not_uploaded.png';
}
?>
You have to place the following inside the table row right to the delete button.
<img src="<?php echo $imageSrc ; ?>" />
Or just place them inside the table row.
if ($vsoi == 'documents/') {
echo '<img src="img_for_uploaded.png" />'
} else {
echo '<img src="img_for_not_uploaded.png" />'
}
Hope this helps you.
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 am working on a little project and I need to display the author's image for each author in my database. peep the code below:
--THE QUERY--
$getboth_sql = mysql_query(
"SELECT lyrics.lyrics_id, lyrics.lyrics_title, lyrics.lyrics_text,artists.artist_nane,artists.artist_id
FROM lyrics,artists
WHERE lyrics.artist_id = artists.artist_id
ORDER BY lyrics.lyrics_title");
while ($both = mysql_fetch_assoc($getboth_sql)) {
$lyrics_id = $both[lyrics_id];
$lyrics_title = $both[lyrics_title];
$lyrics_text = $both[lyrics_text];
$artist_name = $both[artist_nane];
$artist_id = $both[artist_id];
?>
<div class="artimg"><img src="images/artists/<?php echo $artist_name;?>.jpg" height="50px" width="50px"/></div>
<?php
}//END While
The above code work but if I have not saved an image in the 'artists' directory no image show up for that artist.
<div class="artimg"><img src="images/artists/<?php echo $artist_name;?>.jpg" height="50px" width="50px"/></div>
QUESTION: What is the BEST way to display a default image if the specified on is not found.
I have been playing around with the empty and file exists functions but i haven't gotten it right. Please Help.
PS I'm not a pro if this question seems stupid!
There are many ways to do this.
<?php
if(file_exists("images/artists/$artist_name.jpg"))
$fileName = "$artist_name.jpg";
else
$fileName = "default.jpg";
?>
<div class="artimg"><img src="images/artists/<?php echo $fileName;?>" height="50px" width="50px"/></div>
Disk Access = slow
You have a couple of options. One is to check that the file exists each and every time you need to display it. Unfortunately, this is less than ideal because disk reads can be a performance bottleneck. It's not a tenable solution if you're serving up hundreds of page loads a minute. In high-performance environments you want to avoid as many file stats as possible:
$img_dir = '/path/to/artist/images';
$expected_file = $img_dir . '/' . $artist_name . '.jpg';
$img = file_exists($expected_file) ? $artist_name : 'default';
Hard-code the names into your code
Another, if you have a small number of artists whose images you need to display is to hard-code in the names for the images you have:
$authors = array('Bill Shakespeare', 'Douglas Adams', 'Ralph Ellison');
$img = in_array($artist_name, $authors) ? $artist_name : 'default';
Of course, this isn't particularly helpful because then you'll need to edit your code each time your catalog of artist images changes.
The best idea ...
The preferred option in this instance would be this:
Since you're already hitting the database to get the artist records, store the relevant image filename in a database column of the artists table. That way you can avoid the superfluous disk access.
This method allows you to retrieve the filename from the database with your original query. If the field is empty you'll know to display the default image instead.
try
if ( !file_exists( 'images/artists/' . $filename ) ) {
$artist_name = 'holderthumbnail';
}
have holderthumbnail.jpg in your 'artists' directory
Code :
<?php
if(file_exists("$your_image.jpg")) $filename = "$your_image.jpg";
else $filename = "default.jpg";
echo "<img src='$filename'/>";
?>
<img id="currentPhoto" src="SomeImage.jpg" onerror="this.src='Default.jpg'" width="100" height="120">
Try this way: For Laravel:
<?php
$image = parse_url($user->image);
if(isset($image['host'])){
$image= $user->image;
}
else if($image==null){
$image= Request::root().'/uploads'.'/subsystems_icons/'.'democp.jpg';
}
else {
$image= Request::root().'/uploads/'.$user->image;
}
?>
<div class="">
<img class="image" style="width: 100%; height: 300px; object-fit: contain ;"
src="{{$image}}">
</div>
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 . '">';