2011-06-04 81 views
1
while ($topic = mysql_fetch_assoc ($result)); { 
    echo "{$topic["overtag "]} "; 
} 

從我while循環的結果顯示爲這樣: 蘋果橘子香蕉創建一個變量,同時循環導致

我希望能夠把所有這些成果,並把它們放在一個變量,並它看起來像這樣: $ fruits = apple orange banana

我該如何做到這一點?

回答

4

concatination運營商。=

$fruits = ''; 
while ($topic = mysql_fetch_assoc ($result)); { 
    $fruits .= "{$topic["overtag "]} "; 
} 
1

你只需要每一個串聯到變量循環

$fruits = ""; 
while ($topic = mysql_fetch_assoc ($result)); { 
    echo "{$topic["overtag "]} "; 
    $fruits .= $topic['overtag'] . " "; 
} 
// This is going to result in an extra space at the end, so: 
$fruits = trim($fruits); 

哦裏面,另外,你有哪些是要打破一個錯誤分號你while循環:

while ($topic = mysql_fetch_assoc ($result)); { 
            --------^^^-- 

應該是:

while ($topic = mysql_fetch_assoc ($result)) { 
2
// I love arrays. 
$fruits = array(); 
while ($topic = mysql_fetch_assoc ($result)); { 
    $fruits[] = (string)$topic["overtag "]; 
} 

// If you don't want an array, but a string instead, use implode: 

$fruits = implode(' ', $fruits) 
+0

感謝GolezTrol,但是當我這樣做,結果只是說:「陣列」,我的實際陣列沒有出現。 – Samantha 2011-06-04 15:20:50

+0

我在行[] 3上的$ fruits之後擺脫了[]括號,並且給了我想要的結果,但只有當我在while循環內部回顯時。當我在while循環之外回顯$ fruit時,我只得到其中一個結果,這意味着我只能得到「蘋果」而不是「蘋果橙色香蕉」 – Samantha 2011-06-04 15:34:02

+0

如果您願意,可以使用'implode'來演示陣列循環下的代碼行。你當然可以串聯字符串,但實際上在很多情況下,你需要使用從數據庫中檢索的獨立值,這就是爲什麼我把它們放入數組中的原因。數組是保存數據列表的非常強大的工具。如果想將數組中的值轉換爲單個字符串,可以使用'implode'。 – GolezTrol 2011-06-04 21:23:35

1

使用下面的PHP代碼,你可以在網頁從數據庫表並顯示數據:

$sql_query="select * from yourTable"; 
    $result=mysqli_query($connection,$sql_query); 
    if(mysqli_num_rows($result) > 0) 
    { 
     while($row = $result->fetch_array(MYSQLI_ASSOC)) 
     { 
     echo "ID ".$row[0];//echo "ID ".$row["ID"]; 
     echo "Name ".$row[1];//echo "Name ".$row["Name"]; 
     } 
    } 
    else 
    { 
     echo "No Record"; 
    } 
+0

歡迎來到Stack Overflow!儘管此代碼片段可能是解決方案,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-基於代碼的答案)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – yivi 2018-01-19 10:53:35