views:

2155

answers:

5

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\"/>";

}
?>
+4  A: 

What about a simple ternary:

$photo = ($info['photo'] == null) ? "default.jpg" : $info['photo'];
echo "<img class=\"memberImage\" src=images/". $photo .">";
CMS
I tired that but it hasn't displayed the default picture. It displays the uploaded pictures, this is the same problem I had with the code I put up above. Thanks though, did you have any other ideas?
Cool Hand Luke UK
+1  A: 

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.

Patcouch22
+1  A: 

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 .'"/>';
stukelly
+1 Good call. I would do it this way regardless of any database issues.
da5id
A: 

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.

Paul Dixon
A: 

I have managed to fix it now and it works thanks for the suggestions guys. :D

Cool Hand Luke UK