2012-07-04 41 views
1

任何人都可以幫忙 - 這讓我很生氣。

我打電話給一個mysql表,並希望多次顯示結果(或用if語句檢查結果)。但是在這個循環中(見下文),它只在第一個實例($ i = 1)中將該表及其行作爲一個數組調用。這段代碼將構建20個稱爲Box的div,但僅填充表格數據的第一個div。爲什麼?

我認爲我應該在外循環內使用一個foreach循環(我已經得到了這個在wordpress中與那個順便說一句),但無法弄清楚語法。任何幫助將非常感激。

$i=1; 
while ($i <= 20) 
{ 
    echo "<div class=\"Box ".$i."\">"; 
    echo $i; 
    echo "<br>"; 
    while ($row = mysql_fetch_array($result)) 
    { 
    echo $row['name']; 
    } 
    echo "</div>"; 
    $i++; 

} 

回答

1

如果我明白,您正試圖在循環中多次使用相同的結果資源。

第一次循環播放結果資源之後,需要將其倒回到其原始位置以便能夠再次循環播放。它可以與mysql_data_seek($result, 0)倒帶,但更好的策略是將整個事情加載到一個數組的循環之前,然後遍歷每個循環數組:

// Load everything into the array `$results` first. 
$results = array(); 
while ($row = mysql_fetch_assoc($result)) { 
    $results[] = $row['name']; 
} 

// Better an incremental for loop than a while with a counter 
// for a situation where you know the endpoint values of $i 
for ($i = 1; $i <= 20; $i++) 
{ 
    echo "<div class='Box $i'>"; 
    echo $i; 
    echo "<br>"; 
    // Inside your HTML, use the $results array 
    // rather than the MySQL resource 
    foreach ($results as $row) 
    { 
     echo $row['name']; 
    } 
    echo "</div>"; 
} 
+0

是的,這正是我想要做的,謝謝。我嘗試了你的代碼,但我得到了一個解析錯誤 - 意外的'{'第二行之後。什麼是'mysql_fetch_assoc'順便說一句,我是不是使用'mysql_fetch_array'? – gavin

+0

@ user1501500抱歉,錯過了上面修復的關閉')'。 –

+0

@ user1501500'mysql_fetch_array()'返回數字列號和列名作爲鍵,而'mysql_fetch_assoc()'只返回列名作爲鍵。由於您只使用列名'name',因此不需要數字索引,因此'mysql_fetch_assoc()'效率更高一點。 –

0

嘗試這樣做,

$i=1; 
while ($row = mysql_fetch_array($result)) 
{ 
    echo "<div class=\"Box ".$i."\">"; 
    echo $i; 
    echo "<br>"; 
    echo $row['name']; 
    echo "</div>"; 
    $i++; 

} 
+0

嗨。不幸的是,這也不起作用。我以前有過這個結果 - 它爲我的表中的每一行創建了一個「Box」div,每個Box中都有行數據。我需要創建20個(例如)div,並填充每個表中的所有表數據(或者至少用if來檢查所有的表數據) – gavin

+0

我想我需要兩個循環 - 一個迭代數組和另一個循環來重複該迭代×次數。謝謝 – gavin

+0

我看到邁克爾已經提交了一些可以幫助你更好的東西,試試吧。 – itsme

0

一旦mysql_fetch_array($結果)給出,$結果不能再次獲取使用。所以它不會在循環中工作。最好將結果存儲在數組中並在需要時使用它。

+0

謝謝,好主意 – gavin

1

也許我不理解好,但你應該嘗試這個:

$i=1; 
while ($row = mysql_fetch_array($result) && $i <= 20) { 
    echo "<div class=\"Box ".$i."\">"; 
    echo $i; 
    echo "<br>"; 
    echo $row['name']; 
    echo "</div>"; 
    $i++; 
} 

因爲在你的代碼中,你在第一個循環中做你的「mysql循環」。

+0

這是最有效的方法+1 – EaterOfCode

0

您可以使用mysql_data_seek重置爲結果的指針,如果你想通過他們都同時又把,做到:

mysql_data_seek ($result, 0);