0

I have a sql query, but I would like to make sure if someone doesn't upload an avatar (avatar_filename), it will display an alternative avatar (/images/avatars/default.jpg).

I've been looking at if conditionals on this website and tried to used them without success.

This is my working query for the moment:

$query =   "SELECT exp_forum_topics.last_post_author_id, exp_forum_topics.title, exp_forum_topics.topic_id, exp_forum_topics.last_post_date, exp_members.member_id, exp_members.screen_name, exp_members.avatar_filename ".
                        "FROM exp_forum_topics, exp_members ".
                        "WHERE exp_forum_topics.last_post_author_id = exp_members.member_id ".
                        "ORDER BY exp_forum_topics.last_post_date DESC ".
                        "LIMIT 4";

$result = mysql_query($query) or die(mysql_error());

   while ($row = mysql_fetch_array($result)) {

    echo '<img src="/images/avatars/';
    echo $row['avatar_filename'];
    echo '" />';

    echo "<h3><a href='/forum/viewthread/";
    echo $row['topic_id'];
    echo "'>";
    echo $row['title'];
    echo "</a></h3>";

    echo "<p>by <a href='/forum/members/";
    echo $row['last_post_author_id'];
    echo "'>";
    echo $row['screen_name'];
    echo "</a></p>";
 }
1

4 Answers 4

1

Have you considered setting the field (column) in the table with a default value? e.g. DEFAULT='my-image.jpg' or something similar?

Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is what I would do. Simply define a default value in the SQL schema for that column.
1

Define default in column database.

Or...

if (!isset($row['avatar_filename']) {
    echo 'default_avatar.png';
} else {
    echo $row['avatar_filename'];
}

Comments

0

You could check if the returned value is empty and set your default image as follows:

if (!empty($row['avatar_filename'])) {
  echo '<img src="/images/avatars/';
  echo $row['avatar_filename'];
  echo '" />';
} else {
  echo '<img src="/images/avatars/default.jpg" />';
}

1 Comment

Thanks vinodadhikary, exactly what I needed. Perfect!
0

You could handle this in the SQL

in the select list, just replace this:

 exp_members.avatar_filename

with something like:

 COALESCE(NULLIF(exp_members.avatar_filename,''),'default.jpg') 
   AS avatar_filename

That's equivalent to:

 CASE WHEN exp_members.avatar_filename <> ''
      THEN exp_members.avatar_filename
      ELSE 'default.jpg'
 END AS avatar_filename

This essentially emulates the column having a default value of 'default.jpg', by returning that value whenever the column is NULL or is equal to the empty string ''.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.