2012-09-05 36 views
1

是否可以使用mysql運行只有一個查詢mysql,然後做兩個不同的結果while循環。我如何做2 PHP的while循環與1 MySQL的查詢?

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

你試過了嗎?什麼不是這個工作? – bretterer

+0

@bretterer:是的,我試過了,我只得到第一個循環的結果。第二個是空的 – Azukah

+0

在第二個循環之前使用'mysql_field_seek($ qry_offers,0)',但我更喜歡Ansrew的答案! – undone

回答

4

解決方法是保存每個循環的結果,然後將它們放在一起。

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

謝謝隊友!偉大的作品:) – Azukah

+1

+1通過數據集。如果現在他們彼此相鄰,也可以替換第二個。 – Tony

+0

@Tony不使用'else'提供了一個稍微更通用的解決方案,但事實是我沒有看到它。我在PHP中看到的最常見錯誤之一就是無處不在地傳遞大量數據結構,就像結果集一樣。當你閱讀它時,它的可擴展性更好,可以處理結果集,我想鼓勵它。 – staticsan

3

你可以這樣做:

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