0

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

我希望它返回 4 个最近的结果。status在dos = 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++;
                    }
                ?>  
4

2 回答 2

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++;
                }
            }
?>
于 2012-04-05T23:57:16.993 回答
0

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

while($row = $sth->fetch()) { 
        ....
        if($row['status']=='2' && $count >="4") break;
        $count++;
}
于 2012-04-05T23:59:53.467 回答