php 为while循环结果创建变量

kzipqqlq  于 2022-12-10  发布在  PHP
关注(0)|答案(4)|浏览(142)
while ($topic = mysql_fetch_assoc ($result)); {
   echo "{$topic["overtag "]} ";
}

while循环的结果如下所示:苹果橙子香蕉
我希望能够将所有这些结果放入一个变量中,并使它看起来像这样:$水果=苹果橙子香蕉
我怎么能做到这一点?

kkbh8khc

kkbh8khc1#

连接运算符.=

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

zvms9eto2#

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

3df52oht3#

您只需要将每个变量连接到循环内的变量上

$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)) {
rxztt3cl

rxztt3cl4#

使用下面的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";
    }

相关问题