How to select data from a row that has a value

Viewed 48

I am creating a social network that has an explore page. I want to show a post text or an image in two separate divs. The way it shows now isn't what I want.

It shows text and an image in the same div and if there is no image it shows a blank square where the image is supposed to be. It's an explore page so I want the post text and image to show up randomly and in separate divs and if there's nothing in the image div, it'll just show the text and vice versa.

How it shows

$explore_image = $con->prepare('SELECT body, image FROM posts ORDER BY RAND()');
$explore_image->execute();
$explore_image->store_result();
$explore_image->bind_result($body, $image);

// output data of each row
while ($explore_image->fetch()) {
    
    echo '<div id="rcorners2">';
    echo "$body <img src='" . $image . "' id='explore_post_pic'></br><br><br><br>  
            </div><br>" ;
}

UPDATE!!! -

This code only shows one image and one div

$explore_image = $con->prepare('SELECT body, image FROM posts ORDER BY RAND()');
$explore_image->execute();
//$explore_image->store_result();
//$explore_image->bind_result($body, $image);
$explore_image_result = $explore_image->get_result();

while ($row = $explore_image_result->fetch_assoc()) {
    
    //$id = $row['id'];
    $body = $row['body'];
    //$added_by = $row['added_by'];
    //$date_time = $row['date_added'];
    $image = $row['image'];

}           

// output data of each row
if (!empty($image)) {
    # code...

    echo '<div id="rcorners2">';
    echo "<img src='" . $image . "' id='explore_post_pic'></br><br><br><br>  
        </div><br>" ;
}
2 Answers

Remove $explore_image->store_result.
See the documentation. And do not forget to close both the prepared statement and the connection (in this order) after finished.
Based on your initial code:

$explore_image = $con->prepare('SELECT body, image FROM posts ORDER BY RAND()');
$explore_image->execute();
// $explore_image->store_result();
$explore_image->bind_result($body, $image);

// output data of each row
while ($explore_image->fetch())
{
    if (!empty($image))
    {
     echo '<div id="rcorners2">';
     echo "$body <img src='$image' id='explore_post_pic'></br><br><br><br></div><br>";
    }
}
$explore_image -> close();
$con -> close();
<?php

$explore_image = $con->prepare('SELECT body, image FROM posts ORDER BY RAND()');
$explore_image->execute();
$explore_image->store_result();
$explore_image->bind_result($body, $image);

// output data of each row
while ($explore_image->fetch()) {
    
    if($image!=''){
    $newImage="<img src='".$image."' id='explore_post_pic'>";
    }
    else{
    $newImage="";
    }
    
    echo '<div id="rcorners2">'.$body.'</div>';
    echo '<div id="rcorners2">'.$newImage.'</div>';
}

?>
Related