2013-05-13 244 views
0

因此,通常我會像這樣循環訪問數據庫;循環數據庫

while($row = mysql_fetch_array($result)) { 
// echoes here 
} 

這工作正常。但是如果我想對此做些什麼呢?

<h1><?= $row["category_name"]; ?></h1> 
<p><?= $row["description"]; </p> 

while($row = mysql_fetch_array($result)) { 
// echoes here 
} 

這當然不行,因爲mysql_fetch_array是第$row下方。但是像這樣的東西是行不通的。(無限循環)。

$row = mysql_fetch_array($result); 

<h1><?= $row["category_name"]; ?></h1> 
<p><?= $row["description"]; </p> 

while($row) { 
// echoes here 
} 

解決此問題的最佳方法是什麼?第一個回聲的另一個數據庫查詢?

回答

3

第一個:停止使用mysql,其棄用。開始看mysqlipdo

現在我猜你所有的行都包含相同的數據爲category_name,這就是爲什麼你要先打印它。要做到這一點,最簡單的方法就是保持跟蹤,如果你在while循環的第一次迭代。

<?php 
$counter = 0; 
while ($row = mysql_fetch_array($result)) { 
    $counter++; 
    if ($counter==1) { 
    echo '<h1>'.$row['category_name'].'</h1><p>'.$row['description'].'</p>'; 

    //now if your first row only contains this information and doesnt have any regular data, uncomment the continue line. 
    //continue; 
    } 

    //echoes the regular rows. 

} 
?> 

這也可以擴展到檢查類別名稱是否實際更改。所以你可以在改變時打印標題。

<?php 
$header = ""; 
while ($row = mysql_fetch_array($result)) { 
    if ($header!=$row['category_name']) { 
    echo '<h1>'.$row['category_name'].'</h1><p>'.$row['description'].'</p>'; 
    $header = $row['category_name']; 
    } 

    //echoes the regular rows. 
} 
?> 

現在每當類別名稱發生更改時,標題都將打印在說明中。請記住,您的查詢確實需要在category_name上有ORDER BY才能正常工作,否則您可能會得到重複的標頭。

+0

我喜歡這個解決方案!快速簡單,就是我想要的。我也會研究mysqli。我聽說過它,但不知道mysql已被棄用。 – Linkjuice57 2013-05-13 11:27:34

2

只讀取第一行,將指針移至第二行,然後遍歷結果。

$row = mysql_fetch_array($result); 

<h1><?= $row["category_name"]; ?></h1> 
<p><?= $row["description"]; </p> 

mysql_data_seek($result,1); 

while($row= mysql_fetch_array($result)) { 
    // echoes here 
}