循环返回数据

时间:2012-04-05 23:50:25

标签: php loops

在下面的代码中,我将从我的数据库中提取所有即将开始的培训课程。我正在检查endDate是否已经通过,我还在检查status !='2'是否

我希望这能够返回最近的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 个答案:

答案 0 :(得分: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++;
                }
            }
?>

答案 1 :(得分:0)

你可以跳出循环,如果是四个

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