为while循环结果创建变量

时间:2011-06-04 02:28:14

标签: php mysql arrays while-loop echo

while ($topic = mysql_fetch_assoc ($result)); {
   echo "{$topic["overtag "]} ";
}

我的while循环的结果显示如下: 苹果橙香蕉

我希望能够获取所有这些结果并将它们放在变量中并使其看起来像这样: $ fruits =苹果橙香蕉

我怎么能这样做?

4 个答案:

答案 0 :(得分:4)

连接运算符。=

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

答案 1 :(得分:3)

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

答案 2 :(得分: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)) {

答案 3 :(得分:1)

使用下面的PHP代码,您可以从数据库表中获取数据并显示在网页上:

Viewbag.Simple = simpleInteresrt;