If image exists show else hide it - php

I have the following situation.
If there isn't an image in the DB, the page it's on shows a big image placeholder. What is the best way to hide the image placeholder if an image doesn't exist?
<img src="<?php echo '../img/artists/' . $row_rsAccents['artistPhoto']; ?>" width="100%"/>
http://westerndesignconference.com/intheloop/

You can do this with a simple if/else statement like so:
//I prefer to set things with variables
$placeholder_img = "../img/artists/placeholder.jpg";
$db_img = $row_rsAccents['artistPhoto'];
if($db_img){
$img_src = $db_img;
} else {
$img_src = $placeholder_img;
}
echo "<img src='$img_src' alt='' width='100%' />";

If there is a value returned - show an image. If the condition fails, no <img> will be displayed, preventing the blank gap
if (isset($row_rsAccents['artistPhoto'])) {
echo '<img src="../img/artists/' . $row_rsAccents['artistPhoto'] . '" width="100%"/>'
}

if (file_exists('artist.jpg') {
echo "<img src='artist.jpg'>";
}
else {
echo "<img src='default.jpg'>";
}

Related

make an image (background-image CSS) into PHP variable value

I want to make a product gallery like 5 products, each has their own background-image attribute
I use loop to insert the product image, so I want to make it each loop will have different background-image
I'm thinking of using IF statement like so
<?php
$bg = 0;
$bg1 = "url('img1.jpg')";
$bg2 = "url('img2.jpg')";
$bg3 = "url('img3.jpg')";
$bg4 = "url('img4.jpg')";
$bg5 = "url('img5.jpg')";
if ($bg = 0){
echo " <div style='background-image :$bg1 ;'>" ;
$bg = 1;
} else if ($bg= 1) {
echo " <div style='background-image :$bg2 ;'>" ;
$bg = 2;
} else if ($bg= 2 ) {
echo " <div style='background-image :$bg3 ;'>" ;
$bg = 3;
} else if ($bg= 3 ) {
echo " <div style='background-image :$bg4 ;'>" ;
$bg = 4;
} else if ($bg= 4 ) {
echo " <div style='background-image :$bg5 ;'>" ;
$bg = 0;
}
echo " </div> " ;
code for product images
?>
above is the simplified code I wrote, it doesn't work.
if anyone has a different but much simpler solution it will be appreciated
note : the image files are in the same directory with this php file
thank you
Would you be open to using img tags? This, in my opinion, would be a better solution:
Code:
<?php
$images=Array(
"img1.jpg",
"img2.jpg",
"img3.jpg",
"img4.jpg",
"img5.jpg"
);
//
print "\n<br> Code: \n<pre>\n".RenderThoseImages($images)."\n</pre>";
//
function RenderThoseImages($images)
{
//
$s="";
//
foreach($images as $image){
$s.="\n<div><img src=\"{$image}\"></div>";
}
return $s;
}
?>
Outputs:
<br> Code:
<pre>
<div><img src="img1.jpg"></div>
<div><img src="img2.jpg"></div>
<div><img src="img3.jpg"></div>
<div><img src="img4.jpg"></div>
<div><img src="img5.jpg"></div>
</pre>
The main reason being that when you use the background-image CSS, you're also responsible for grabbing the image dimensions in PHP and rendering height/width into the div CSS as well, or possibly creating some javascript to fix it after loading, creating unneeded headache.

Can't load image from MySQL database with PHP

I'm creating a list of articles inside a section, but I'm having troubles getting the images out of my MySQL database. I followed this guide how to store images in MySQL http://forums.mysql.com/read.php?20,17671,27914. This is the code I'm using.
<?php
$result = mysql_query("SELECT * FROM heroes");
while ($row = mysql_fetch_array($result)) {
echo "<article>";
if($row{'Type'} == 'Strength') {
echo "<span class='strength'></span>";
} elseif ($row{'Type'} == 'Agility') {
echo "<span class='agility'></span>";
} else {
echo "<span class='intelligence'></span>";
}
echo "<div>";
echo "<header>"."<h2>"."<a href='javascript:;'>".$row{'Name'}."</a>"."</h2>"."</header>";
if($row{'Image'} != NULL) {
?>
<img src="<?php base64_decode($row{'Image'}); ?>" alt="hero-image" width="200" height="300" />
<?php
} else {
echo '<img src="images/no-image.png" alt="hero-image" width="200" height="300" />';
}
echo "</div>";
echo "</article>";
}
?>
replace your image source with
'data:image/gif;base64,'.base64_decode($row{'Image'});
also use proper mime instead of gif
There are a few things wrong with your code:
You call mysql_fetch_array but then use curly braces which are meant for objects, yet you have an array.
You call base64_decode. This means that you will get binary content into your HTML which won't work. You have to encode it with base64_encode if it is stored in binary form.
The value of the src of a <img> must be a URL, not the content itself. In your case you can use a Data-URL.

Wordpress Custom Field using Advanced Custom Fields

I am having some trouble modifying a plugin WordPress popular posts I installed.
It has the option to fetch thumbnails from a custom field, which I have entered as "image_facebook". But the thumbnails are not being displayed.
While checking the code I found that img src has post id instead of returning image URL.
"<img src="5438" width="135" height="135" alt="Alt text" border="0" />"
I have narrowed down the problem to another plugin which I have installed http://wordpress.org/plugins/advanced-custom-fields/ and while it is active I have to use "the_field ()" to fetch the custom field content instead of regular WordPress "get_post_meta" It is documented here http://www.advancedcustomfields.com/resources/functions/the_field/
I need to edit the below code in the WordPress popular posts file to use the_field() function. The code in the WordPress-popular-posts.php says:-
// POST THUMBNAIL
if ($instance['thumbnail']['active'] && $this->thumb) {
$tbWidth = $instance['thumbnail']['width'];
$tbHeight = $instance['thumbnail']['height'];
$thumb = "<a href=\"". $permalink ."\" title=\"{$title}\" target=\"".$this->user_ops['tools']['link']['target']."\">";
if ( $this->user_ops['tools']['thumbnail']['source'] == "custom_field" ) { // get image from custom field
$path = get_post_meta($p->id, $this->user_ops['tools']['thumbnail']['field'], true);
if ( $path != "" ) {
if ( $this->user_ops['tools']['thumbnail']['resize'] ) {
$thumb .= $this->get_img( $p->id, array($tbWidth, $tbHeight), $this->user_ops['tools']['thumbnail']['source'] );
} else {
$thumb .= "<img src=\"{$path}\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" alt=\"{$title}\" border=\"0\" />";
}
} else {
$thumb .= "<img src=\"". $this->default_thumbnail ."\" alt=\"{$title}\" border=\"0\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" />";
}
} else { // get image from post / Featured Image
$thumb .= $this->get_img( $p->id, array($tbWidth, $tbHeight), $this->user_ops['tools']['thumbnail']['source'] );
}
//$thumb .= "</a>";
}
In my theme files I am able to retrieve the Image URL via the following code:-
<img src="<?php echo get_field('image_facebook'); ?>" alt="<?php the_title(); ?>" class="postImg" />
Please help me put this function in the plugin code above.
UPDATE
Ok so with the below code, the image URL is fetched but it is fetching the same image URL for all 10 popular posts.
// POST THUMBNAIL
if ($instance['thumbnail']['active'] && $this->thumb) {
$my_image = get_field('image_facebook');
$my_title = get_the_title();
$tbWidth = $instance['thumbnail']['width'];
$tbHeight = $instance['thumbnail']['height'];
$thumb = "<a href=\"". $permalink ."\" title=\"{$title}\" target=\"".$this->user_ops['tools']['link']['target']."\">";
if ( $this->user_ops['tools']['thumbnail']['source'] == "custom_field" ) { // get image from custom field
$path = get_post_meta($p->id, $this->user_ops['tools']['thumbnail']['field'], true);
if ( $path != "" ) {
if ( $this->user_ops['tools']['thumbnail']['resize'] ) {
$thumb .= $this->get_img( $p->id, array($tbWidth, $tbHeight), $this->user_ops['tools']['thumbnail']['source'] );
} else {
//$thumb .= "<img src=\"{$path}\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" alt=\"{$title}\" border=\"0\" />";
$thumb .= "<img src=\"" . $my_image . "\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" alt=\"" . $my_title . "\" border=\"0\" />";
}
} else {
$thumb .= "<img src=\"". $this->default_thumbnail ."\" alt=\"{$title}\" border=\"0\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" />";
}
} else { // get image from post / Featured Image
$thumb .= $this->get_img( $p->id, array($tbWidth, $tbHeight), $this->user_ops['tools']['thumbnail']['source'] );
}
//$thumb .= "</a>";
}
<img src="5438" width="135" height="135" alt="Alt text" border="0" />
If this is your only problem, you can modify the value that the ACF image field returns. Right now it is probably set to Image ID. Try setting it to Image URL instead:
In case that doesn't help, I would try this. Keep in mind I don't understand how your plugin interacts with ACF. First I would set your variables:
$my_image = get_field('image_facebook');
$my_title = get_the_title();
Then I would replace every instance of $thumb .= with your functioning ACF code, just to test, like this:
$thumb .= "<img src=\"" . $my_image . "\" alt=\"" . $my_title . "\" class=\"postImg\" />";

How to pull only 1 image from folder in php?

I have working code, which pulls all images from a dynamically created folder. But I want to display only 1 image from a particular folder in my display page. Any suggestions?
My code:
<?php
$search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
$images = glob("$search_dir/*.jpg");
sort($images);
//display images
foreach ($images as $img) {
echo "<img src='$img' height='150' width='150' /> ";
}
?>
You can display a single image with:
<?php
$search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
$images = glob("$search_dir/*.jpg");
sort($images);
// Image selection and display:
//display first image
if (count($images) > 0) { // make sure at least one image exists
$img = $images[0]; // first image
echo "<img src='$img' height='150' width='150' /> ";
} else {
// possibly display a placeholder image?
}
?>
If you want a random image, do this:
// Image selection and display:
//display random image
if (count($images) > 0) { // make sure at least one image exists
// Get a random index in the array with rand(min, max) which is inclusive
$randomImageIndex = rand(0, count($images)-1);
$img = $images[$randomImageIndex]; // random image
echo "<img src='$img' height='150' width='150' /> ";
} else {
// possibly display a placeholder image
}
You can use current to get the first image from the array.
<?php
$search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
$images = glob("$search_dir/*.jpg");
sort($images);
//display one image:
echo "<img src='current($images)' height='150' width='150' /> ";
?>

PHP If else statement that a database record is empty it will display a default picture

Hi basicly I am trying to create a simple IF statement that shows a default picture if one hasn't been entered in to my database. I am using server to store my picture and a database to store the file name, so I can get the image to display if it has a file name in the db but I want the If statement to say if the record is empty display this default image. I have some code here that I have tried however it doesn't work any thoughts? I tried a few other ways of doing it but they didn't work either.
Cheers.
Code so far:
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM db*****") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<div class="member">
<div class="imageSection">
<?
if($info['photo'] == '')
{echo "<img class=\"memberImage\" src=images/default.jpg>";}
else {echo "<img class=\"memberImage\" src=images/".$info['photo'] .">";}
?>
</div>
<div class="memberInfo">
<? Echo "<p><strong>Name: ".$info['nameMember'] . "</strong></p>";
Echo "<p>Position: ".$info['bandMember'] . " </p>";
Echo "<p>About Band Member ".$info['nameMember'] .":".$info['aboutMember'] . "</p>";
Echo "<p>Other Bands: ".$info['otherBands'] . " </p><br/></div></div><br class=\"clearBoth\"/>";
}
?>
What about a simple ternary:
$photo = ($info['photo'] == null) ? "default.jpg" : $info['photo'];
echo "<img class=\"memberImage\" src=images/". $photo .">";
Are you sure the default value for the column is set to "". it could be set to null? although idk if that would cause it not work.
add the following code before the if statement
echo $info['photo'];
Another suggestion would be to trim the data before comparing it.
You could use file_exists, which will work even if the image is deleted manually.
$photo = 'images/'. $info['photo'];
if (file_exists($photo) == FALSE)
{
$photo = 'images/default.jpg';
}
echo '<img class="memberImage" src="'. $photo .'"/>';
empty() can catch the sort of conditions you are after, so try
if(empty($info['photo']))
{
....
}
empty() returns true if the parameter is '', NULL, false, '0', 0, or an empty array.

Categories