简单查询返回ELSE块中的结果而不是IF

时间:2017-08-02 07:53:24

标签: php mysql pdo

请原谅我的“新手”问题,但我对简单的pdo查询有问题。我所拥有的是从两个表中查询并基于user_id来显示他上传的所有图像。这是代码

$sql = "SELECT * FROM user_images      
        LEFT JOIN users 
        ON user_images.user_id = users.id
        WHERE user_images.user_id=:user_id";
$stmt = $db_con->prepare($sql);
$stmt->bindParam(":user_id", $_SESSION['user']['id']);      
$stmt->execute();
$user_photos = $stmt->fetch();

if (is_object($user_photos) && !empty($user_photos) && $user_photos->num_rows > 0) {
     while ($row = $user_photos->fetch_assoc()) { ?>
          <img src="uploads/<?php echo $row->images_name; ?>"> 
     <?php }} else { ?>
     <li style="text-align: center">
           No Images Found!
     </li>
<?php } ?>

这里发生的是IF阻止图像没有显示。相反,如果我在var_dump($row->images_name);阻止ELSE阻止图像可见。

2 个答案:

答案 0 :(得分:1)

$sql = "SELECT * FROM user_images      
        LEFT JOIN users 
        ON user_images.user_id = users.id
        WHERE user_images.user_id = ?";
$stmt = $db_con->prepare($sql);     
if ($stmt->execute(array($_SESSION['user']['id']))) {
    while ($row = $stmt->fetch()) {
        echo '<img src="uploads/', $row['images_name'], '">'; 
    }
}
if (empty($row)) { ?>
     <li style="text-align: center">
           No Images Found!
     </li>
<?php } ?>

答案 1 :(得分:0)

另一种使用php函数count()的方法。

<?php
$sql = "SELECT * FROM user_images      
        LEFT JOIN users 
        ON user_images.user_id = users.id
        WHERE user_images.user_id=:user_id";
$stmt = $db_con->prepare($sql);
$stmt->bindParam(":user_id", $_SESSION['user']['id']);      
$stmt->execute();
$user_photos = $stmt->fetchAll();

if (count($user_photos) > 0) {        
     foreach ($user_photos as $row) {
         echo '<img src="uploads/'.$row['images_name'].'">';
     } 
} else {
      echo '<li style="text-align: center">No Images Found!</li>';
}