如何做2个php while循环与1 mysql查询?

时间:2012-09-05 01:58:07

标签: php mysql

是否可以使用php& amp;运行一个查询mysql然后做两个while循环,结果不同。我

//this is the query
$qry_offers = mysql_query("SELECT * FROM offers ORDER BY offer_end ASC");

在第一个循环中,我想显示任何“end_date”小于或等于今天的结果

<div id="current">
<?
while($row_offers = mysql_fetch_assoc($qry_offers)) {
    if ( (date("Y-m-d H:i:s")) <= ($row_offers['offer_end']) ) {
        echo '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
    }
}
?>
</div><!-- END OF CURRENT -->

在第二个循环中,我想显示任何“end_date”大于今天的结果

//this is where i would have the 2n while loop
<div id="inactive">
<?
   while($row_offers = mysql_fetch_assoc($qry_offers)) {
    if ( (date("Y-m-d H:i:s")) > ($row_offers['offer_end']) ) {
        echo '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
    }
}
?>
</div><!-- END OF INACTIVE -->

2 个答案:

答案 0 :(得分:5)

解决方案是保存每个循环的结果,然后将它们放在一起。

$offers_current = array();
$offers_inactive = array();

while($row_offers = mysql_fetch_assoc($qry_offers)) {
    if ( (date("Y-m-d H:i:s")) <= ($row_offers['offer_end']) )
        $offers_current[] = '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
    if ( (date("Y-m-d H:i:s")) > ($row_offers['offer_end']) )
        $offers_inactive[] = '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
}

?>
<div id="current">
    <ul>
    <?php echo implode("\n", $offers_current) ?>
    </ul>
</div>
<div id="inactive">
    <ul>
    <?php echo implode("\n", $offers_inactive) ?>
    </ul>
</div>

答案 1 :(得分:4)

你可以这样做:

$itemsArray = mysql_fetch_assoc($qry_offers);
foreach ( $itemsArray as $row_offers ) {
    // ... Code in here for less than 'offer_end'
}
foreach ( $itemsArray as $row_offers ) {
    // ... Code in here for greater than 'offer_end'
}