PHP:在 while 循环中将字符串分隔为 html 元素


PHP: comma separated string to html elements in the while loop?

我正在尝试从存储在 MYSQL 数据库中的逗号分隔字符串创建单选按钮。

但是,我只得到逗号分隔字符串的最后一个值,因此它只创建 1 个单选按钮,而实际上它应该创建多个单选按钮,因为有这样的字符串:

1,2,3,4

我的 PHP mysql 查询如下所示:

list = "";
$sql2 ="SELECT * FROM table";
$query2 = mysqli_query($db_conx, $sql2);
$productCount = mysqli_num_rows($query2); // count the output amount
if ($productCount > 0) {
    while($row = mysqli_fetch_array($query2, MYSQLI_ASSOC)){ 
             $column = $row["column"];

             $drawes ="";
             $mark=explode(",", $Draw);
             foreach($mark as $out) {
             $drawes = '<label for="one">
             <input type="radio" id="one" name="duration" value="1" />
             '.$out.'
             </label>';
   }

list .= '<div style="width:100%; height:auto; border-bottom:solid 1px #CCC; padding-bottom:10px;padding-top:10px;">
'.$drawes.'
</div>';
}
}

我在我的页面上echo $list;,但我的页面上只有 1 个单选按钮,字符串的最后一个值如下所示:

<label for="one">
<input type="radio" id="one" name="duration" value="1" />
4
</label>

有人可以就此问题提供建议吗?

提前谢谢。

您正在执行循环中$drawes的作业。变量的当前内容将被覆盖。

似乎您想连接到现有值。

PHP 连接赋值运算符是 " .="。

$a = 'this';
$a .= 'and something else';
echo $a;

代码中的错误太多。我已经重写了我可以测试的部分。sql 位没有经过测试,我假设您正在提取正确的数据。将我的代码与您的代码进行比较,您会发现传递了一些错误的变量,并且还缺少连接。

$list = "";
$sql2 ="SELECT * FROM table";
$query2 = mysqli_query($db_conx, $sql2);
$productCount = mysqli_num_rows($query2); // count the output amount
if ($productCount > 0)
{
    while($row = mysqli_fetch_array($query2, MYSQLI_ASSOC))
    { 
        $column = $row["column"];
        $drawes = "";
        $mark = explode(",", $column);
        foreach($mark as $out)
        {
            $drawes .= '<label for="one">'.$out.'</label>
            <input type="radio" id="one" name="duration" value="'.$out.'" /><br>';
        }
        $list .= '<div style="width:100%; height:auto; border-bottom:solid 1px #CCC; padding-bottom:10px;padding-top:10px;">'.$drawes.'</div>';
    }
}