Reputation: 3
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>";
}
Upvotes: 0
Views: 1163
Reputation: 38645
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" />';
}
Upvotes: 0
Reputation: 555
Define default in column database.
Or...
if (!isset($row['avatar_filename']) {
echo 'default_avatar.png';
} else {
echo $row['avatar_filename'];
}
Upvotes: 1
Reputation: 108500
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 ''
.
Upvotes: 0
Reputation: 2483
Have you considered setting the field (column) in the table with a default value? e.g. DEFAULT='my-image.jpg' or something similar?
Upvotes: 1