I cannot figure out how to do the following:
I am sending JSON data in my php file to be displayed, the only issue is this line:
$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
The reason it is an issue is because it is only checking for profile pictures within the database. Well, the system I created a user will either have their original default image or the one they uploaded. So, this issue is if there is a default image, then they do not have an image to be pulled from the database. So I am trying to figure out a way to check for the $row['img']
or if not, then display the default.
The default image is mapped like this: <img class="home-profile-pic" src="profile_images/default.jpg">
Am I am able to have an if statement under the foreach and then set a variable for this? If so, how?
foreach ($rows as $row) {
$html = "";
//$html .= '<div class="comment-post-box">';
$html .= '<div class="comment-post-box" id="comment-'.$row['id'].'">';
$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
$html .= '<div class="comment-post-username">'.$row['username']. '</div>';
$html .= '<div>'.$row['date']. '</div>';
$html .= '<div class="comment-post-text">'.$row['comment']. '</div>';
$html .= '</div>';
$data = array('id' => $row['id'], 'date' => $row['date'], 'html' => $html);
$comments[] = $data;
}
EDIT
$user = new User();
//Get the last insert id
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
$select_comments_stmt->execute();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
$comments = array();
foreach ($rows as $row) {
$html = "";
$html .= '<div class="comment-post-box" id="comment-'.$row['id'].'">';
//$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
$html .= sprintf(
'<img class="home-comment-profile-pic" src="%s">',
empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
);
$html .= '<div class="comment-post-username">'.$row['username']. '</div>';
$html .= '<div>'.$row['date']. '</div>';
$html .= '<div class="comment-post-text">'.$row['comment']. '</div>';
$html .= '</div>';
$data = array('id' => $row['id'], 'date' => $row['date'], 'html' => $html);
$comments[] = $data;
}
}
echo json_encode($comments);