简单的if else语句不能正常工作

时间:2016-05-24 13:36:51

标签: php

我得到了一个简单的if else语句,其中我显示了pdf文件列表,当id为空时(也就是没有pdf文件)我想显示:'没有可用的下载'。但它显示文本无论如何,即使存在pdf文件。

我的代码:

<div class="widget broucher">
    <h4>DOWNLOADS</h4>
    <ul>
    <?
    //pdf bestanden
    $pdf                = "SELECT * FROM `snm_attachments` WHERE parent_id = '".$conn->real_escape_string($contentcr[0]['id'])."'";
    $pdfcon             = $conn->query($pdf);
    $pdfcr              = array();
    while ($pdfcr[]     = $pdfcon->fetch_array());

    foreach($pdfcr as $pdf){
        if($pdf['id'] != ''){
            $downloads .= '<li><a href="cms/attachments/article/'.$contentcr[0]['id'].'/'.$pdf['filename'].' "target="_blank"><i class="fa fa-file-pdf-o"></i>'.$pdf['filename'].'</a></li>';   
        }else{
            $downloads .= '<li>No available downloads</li>';
        }
    }
    echo $downloads;
    ?>
    </ul>
</div>

为什么它总是显示,即使行中没有id

1 个答案:

答案 0 :(得分:0)

使用此代码:

<?
//pdf bestanden
$pdf                = "SELECT * FROM `snm_attachments` WHERE parent_id = '".$conn->real_escape_string($contentcr[0]['id'])."'";
$pdfcon             = $conn->query($pdf);

// initialize downloads variable:
$downloads = '';

// see how while statement disappears (in your code you have the fetch_array attached to the first element of the array):
$pdfcr              = $pdfcon->fetch_array();

foreach($pdfcr as $pdf){
    if($pdf['id'] != ''){
        $downloads .= '<li><a href="cms/attachments/article/'.$contentcr[0]['id'].'/'.$pdf['filename'].' "target="_blank"><i class="fa fa-file-pdf-o"></i>'.$pdf['filename'].'</a></li>';   
    }else{
        $downloads .= '<li>No available downloads</li>';
    }
}
echo $downloads;
?>

注意,当id不为空时,将在数据数组的所有迭代中呈现No available downloads消息。要在没有记录时显示消息,请使用以下代码:

if(count($pdfcr) > 0) {
  foreach($pdfcr as $pdf){
    if($pdf['id'] != ''){
        $downloads .= '<li><a href="cms/attachments/article/'.$contentcr[0]['id'].'/'.$pdf['filename'].' "target="_blank"><i class="fa fa-file-pdf-o"></i>'.$pdf['filename'].'</a></li>';   
    }
  }
}