2016-05-24 119 views
0

我得到了一個簡單的if else語句,其中我顯示了pdf文件的列表,當id爲空時(又名沒有pdf文件)我想顯示:'沒有可用的下載' 。但是,即使存在pdf文件,也可以顯示文本。簡單如果else語句不能正常工作

我的代碼:

<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目前對於行?

+0

使用if(!isset($ PDF [ '身份證'])&& $ PDF [ '身份證'] = ''),而不是 –

+0

爲什麼你做你的代碼如此複雜,使用'while和foreach循環'在一起。你可以使用單一的while循環! – Saty

+1

使用var_dump($ pdf ['id'])來檢查輸出是什麼 –

回答

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; 
?> 

注比No available downloads消息將在所述數據陣列的所有迭代被渲染時id爲大於空不同。爲了顯示該消息時沒有記錄使用此代碼:

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>'; 
    } 
    } 
} 
+0

這給出了以下警告:'警告:在/ home/website/public_html/_intern/web/content.php在線100上的非法字符串偏移'id'並且循環pdf約15次以及沒有可用下載文本 – twan

+0

把'var_dump($ pdfcr)'告訴我們什麼返回 –

+0

這裏是輸出:http://collabedit.com/ty53y – twan