使用 php 从 db 循环填充 multi-select
Populate multi-select with php while loop from db
以下内容适用于本地环境。既然推了
生活的一切,但这些似乎工作。现在显示完全空的 select 框,在 "select options" 下拉列表中没有检查或空白标签只是空的 space。
select display
<?php
$selected = array();
$selected = explode(",",$fill['markets']);
$condb = mysql_query("SELECT * FROM `countries`");
$count = mysql_num_rows($condb);
$countries = array();
$str;
while ($countries = mysql_fetch_array($condb))
{
$str = "option{$countries['id']}";
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
}
?>
您应该改用 while 循环。如果需要可以在循环外声明$i
,试试下面的代码:
$condb = mysql_query("SELECT * FROM `countries`");
$i = 0;
while($countries = mysql_fetch_array($condb)) {
$str = 'option' . $i;
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
$i++;
}
?>
</select>
注:
mysql_*
自 php-5.5 起已弃用。所以改用 mysqli_*
或 PDO
.
Why shouldn't I use mysql_* functions in PHP?
以下内容适用于本地环境。既然推了 生活的一切,但这些似乎工作。现在显示完全空的 select 框,在 "select options" 下拉列表中没有检查或空白标签只是空的 space。 select display
<?php
$selected = array();
$selected = explode(",",$fill['markets']);
$condb = mysql_query("SELECT * FROM `countries`");
$count = mysql_num_rows($condb);
$countries = array();
$str;
while ($countries = mysql_fetch_array($condb))
{
$str = "option{$countries['id']}";
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
}
?>
您应该改用 while 循环。如果需要可以在循环外声明$i
,试试下面的代码:
$condb = mysql_query("SELECT * FROM `countries`");
$i = 0;
while($countries = mysql_fetch_array($condb)) {
$str = 'option' . $i;
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
$i++;
}
?>
</select>
注:
mysql_*
自 php-5.5 起已弃用。所以改用 mysqli_*
或 PDO
.
Why shouldn't I use mysql_* functions in PHP?