1
votes

the below while loop statement loops mysqli query result(text and image from database). A row can contain text only or image and text. I'm trying to display text only if the image field is empty and display both image and text when they both exist in a row. However, i tried using the if statement in the while loop statement below, the problem is that when it suppose to display only text,it displays text with image tag with no src value,kindly help fix this. Thanks.

while($row = mysqli_fetch_assoc($query)){
    $id = $row["id"];
    $text = $row["texts"];
    $image =$row['images']; 
    if(!empty($text) && !empty($image)){
        echo '<img src='.$image.'/>';
        echo '<div>'.$text.'</div>';
    }elseif( !empty($text) && empty($image) ){
        echo '<div>'.$text.'</div>';
    }
}
2
We cannot help here, since we do not know the data you are working with. - arkascha
So what does $image actually contain exactly? - arkascha
@arkascha image location url - boost
You want to think about that last comment again, I suggest. - arkascha
If this is echo'ing the <img> tag, $image is not empty. If you var_dump($image); what does it say for those cases where it's now echo'ing an empty <img> tag? - rickdenhaan

2 Answers

0
votes

$row['images'] might contain spaces, try trimming it. Also, you can simplify the if:

while($row = mysqli_fetch_assoc($query)){
    $id = $row["id"];
    $text = trim($row["texts"]);
    $image = trim($row['images']); 
    if(!empty($image)){
        echo '<img src='.$image.'/>';
    }
    if(!empty($text)){
        echo '<div>'.$text.'</div>';
    }
}
0
votes
while($row = mysqli_fetch_assoc($query)){
   $id = $row["id"];
   $text = $row["texts"];
   $image =$row['images']; 

   if($image)
      echo "<img src='{$image}' />";
   if($text)
      echo "<div>{$text}</div>";

}