2012-04-05 93 views
0

在下面的代碼中,我將從我的數據庫中提取所有即將開始的培訓課程。我在檢查endDate是否已通過,並且我還在檢查是否需要返回4個最新結果。它工作正常,直到status確實= 2。我知道該循環在技術上運行4次,但只顯示結果與status !='2'循環返回數據

我該如何改變這個,以便如果status = '2'循環將繼續,直到它找到4個符合條件的結果?

<?php 
$today = date("Y-m-d"); 
$count = 0; 
$sth = $dbh->query('SELECT * from training ORDER BY startDate ASC'); 
     $sth->setFetchMode(PDO::FETCH_ASSOC); 
      while($count <= 4 && $row = $sth->fetch()) { 
       if($row['endDate'] > $today && $row['status'] != '2') {?> 
        <li> 
        <img class="post_thumb" src="/images/img.jpg" alt="" /> 
        <div class="post_description"> 
         <small class="details"> 
          <?php echo date("m/d/Y", strtotime($row['startDate'])) . ' - ' . date("m/d/Y", strtotime($row['endDate'])) ?> 
         </small> 
         <a class="post_caption" href="/register.php?course_id=<?php echo $row['courseId'] . '&id=' . $row['id'] ?>"><?php echo $row['title'] ?></a> 
        </div> 
        </li> 
       <?php } 
        $count++; 
        } 
       ?> 

回答

2

你必須把$count++if循環內,否則總是會得到增加。 如:

<?php 
$today = date("Y-m-d"); 
$count = 0; 
$sth = $dbh->query('SELECT * from training ORDER BY startDate ASC'); 
     $sth->setFetchMode(PDO::FETCH_ASSOC); 
      while($count <= 4 && $row = $sth->fetch()) { 
       if($row['endDate'] > $today && $row['status'] != '2') {?> 
        <li> 
        <img class="post_thumb" src="/images/img.jpg" alt="" /> 
        <div class="post_description"> 
         <small class="details"> 
          <?php echo date("m/d/Y", strtotime($row['startDate'])) . ' - ' . date("m/d/Y", strtotime($row['endDate'])) ?> 
         </small> 
         <a class="post_caption" href="/register.php?course_id=<?php echo $row['courseId'] . '&id=' . $row['id'] ?>"><?php echo $row['title'] ?></a> 
        </div> 
        </li> 
       <?php 
       $count++; 
       } 
      } 
?> 
+0

啊哈!完善!謝謝! – 2012-04-06 00:02:47

0

可以打破圈外的,如果它的四個

while($row = $sth->fetch()) { 
     .... 
     if($row['status']=='2' && $count >="4") break; 
     $count++; 
}