如何在PHP中循环多选标签和选项[duplicate]

dddzy1tm  于 2023-01-12  发布在  PHP
关注(0)|答案(3)|浏览(425)
    • 此问题在此处已有答案**:

How to fetch values to select/option tags from MySQL(1个答案)
Drop down menu with php/mysql query - echoing information of selected item(1个答案)
Set Select Options Equal To MySQL Query(1个答案)
Using MYSQLI to populate dropdown box - PHP(2个答案)
Select options from mysql query(2个答案)
昨天关门了。
Multiple select tag by loop
这是我已经做了,但我还想显示所有的值在选项下拉菜单中选择。我怎么做呢?
这是编码

$sql = $connect->prepare("SELECT * FROM mapping");

$sql->execute();
$result = $sql -> get_result();

$count = $result->num_rows;

 if($count > 0)
 {
  $namecsv = null;

    while($row = $result->fetch_assoc())
    {
           //key              //value
      $namecsv[$row['name_csv']] = $row['name_db_col'];
      
    }
    foreach($namecsv AS $name => $value)
      {
        echo "<select><option value='$value'>$name</option></select>";
      }
  }
s8vozzvw

s8vozzvw1#

代码需要修改一点,以便在同一个下拉列表中获取值和列表-
你可以试试这个,

if($count > 0)
 {
  $namecsv = null;

    while($row = $result->fetch_assoc())
    {
           //key              //value
      $namecsv[$row['name_csv']] = $row['name_db_col'];
      
    }
    echo "<select>";
    foreach($namecsv AS $name => $value)
      {
        echo "<option value='$value'>$name</option>";
      }
    echo "</select>";
  }
xoshrz7s

xoshrz7s2#

<select>移出循环,现在为每个<option>创建单独的<select>元素:

$sql = $connect->prepare("SELECT * FROM mapping");

$sql->execute();
$result = $sql->get_result();

$count = $result->num_rows;

 if($count > 0)
 {
    $options = [];

    while($row = $result->fetch_assoc())
    {
        $options[] = "<option value='{$key}'>{$value}</option>";
    }

    $options = PHP_EOL . implode(PHP_EOL, $options) . PHP_EOL;

    foreach ($options as $option) {
        echo '<select>' . $options . '</select>';
    }
  }

PHP_EOL常量只是一个换行符,如果需要,可以将其删除。

2vuwiymt

2vuwiymt3#

你能试试这个吗:

enter code here$sql = $connect->prepare("SELECT * FROM mapping");

$sql->execute();
$result = $sql->get_result();

$count = $result->num_rows;

if($count > 0) {
    $select = '<select>';
    while($row = $result->fetch_assoc())
    {
        $select .= "<option value='".$row['name_csv']."'>".$row['name_db_col']."</option>";
    }
    $select .= '</select>';
}

相关问题