echo image according to a condition

2019-02-21 07:14发布

问题:

I have an HTML tag here :

<span class="fa-stack fa-5x has-badge" >
    <div class="badgesize">
        <img src="badgeImages/1.png"  alt=""   >
    </div>
</span> -->

Query used to retrieve info and store it in a variable :

$q4 = "SELECT TOP 3 b.BadgeName, b.BadgeImage FROM BadgeImageTable AS b
INNER JOIN employee_badge AS e
ON e.badge_id = b.BadgeID
WHERE e.employee_id = 2164
ORDER BY e.earned_on DESC ";
$stmt3=sqlsrv_query($conn,$q4);
if($stmt3==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}

In the image tag I am trying to echo an the image of a badge with some condition.

<span class="fa-stack fa-5x has-badge" >

        <div class="badgesize">

            <img src="

<?php

if($count = sqlsrv_num_rows($stmt3) > 0){
while($recentBadge = sqlsrv_fetch_array($stmt3)){
$result[] = $recentBadge;
}

if($count > 3){
$result = array_rand($result, 3);
                      }

foreach($result as $recentBadge){
echo
$recentBadge['BadgeName'],
'<img src="'.$recentBadge['BadgeImage'].'">',
'<br>'
  ;
  }
  } else {
  echo 'no results';
      }

      ?>

      "  alt=""  >

    </div>

</span>

Condition of above PHP:

I want to echo any three random images if the count is greater than 3, else echo whatever '$recentBadge' gives as the result.

Problem: I am unable to echo according to the above condition.

Whenever I try to echo a simple image without any condition(using below PHP), I am able to do so without any issue. So, I am able to fetch the image from the DB, problem lies with the conditional PHP.

    <img src="<?php echo "".($badgerecent['BadgeImage']).""; ?>" >

回答1:

The output from your code was putting <img> tags inside the src attribute of the tag.
That by definition doesn't work in HTML. If everything else was right, this should work:

<?php

function get_random_elements( $array,$limit = 0 ) {

    shuffle($array);

    if ( $limit > 0 ) {
        $array = array_splice($array, 0, $limit);
    }
    return $array;
}

function render_images() {
    global $stmt3;
    $output = '';

    if ($count = sqlsrv_num_rows($stmt3) > 0) {
        while ($recentBadge = sqlsrv_fetch_array($stmt3)) {
            $result[] = $recentBadge;
        }

        if ($count > 3) {
            $result = get_random_elements(result, 3);
        }

        foreach ($result as $recentBadge) {
            $output .= $recentBadge['BadgeName'];
            $output .= '<img src="' . $recentBadge['BadgeImage'] . '" alt="">';
            $output .= '<br>';
        }
    } else {
        $output = 'no results';
    }

    return $output;
}
?>

<span class="fa-stack fa-5x has-badge" >

    <div class="badgesize">

        <?php echo render_images(); ?>

    </div>

</span>

As a tip: please try to keep your code separated, the logic separated from the view.