Azukah
Azukah

Reputation: 227

how to do 2 php while loops with 1 mysql query?

is it possible to run only one query using php & mysql and then do two while loops with different results. i

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

in the first loop, i want to show any result which has an "end_date" less or equal than today

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

in the second loop, i want to show any result which has an "end_date" greater than today

//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 -->

Upvotes: 1

Views: 1627

Answers (2)

staticsan
staticsan

Reputation: 30555

The solution is to save the results from each loop and then put them together at the end.

$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>

Upvotes: 5

Andrew Jackman
Andrew Jackman

Reputation: 13966

You could do this:

$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'
}

Upvotes: 4

Related Questions