1

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>';
    }
}
6
  • We cannot help here, since we do not know the data you are working with. Commented May 9, 2017 at 21:14
  • So what does $image actually contain exactly? Commented May 9, 2017 at 21:15
  • @arkascha image location url Commented May 9, 2017 at 21:16
  • You want to think about that last comment again, I suggest. Commented May 9, 2017 at 21:17
  • 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? Commented May 9, 2017 at 21:17

2 Answers 2

0

$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>';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
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>";

}

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.