从数据库中创建三个下拉列表

时间:2018-04-16 09:39:24

标签: php html database list

必须从数据库中创建三个下拉列表。我尝试了两种方法,第一种方法不起作用,它只创建一个42个字符的字符串(var_dump显示)。第二个显示第一个列表和第一个电话。有什么问题?

$query2 = 
    'SELECT
        `phone_1`, `phone_2`, 
        `phone_3`, `phone_4`, 
        `phone_5`
     FROM 
        phones_users';

$resultPhones = mysqli_query($con, $query2);
$count_Phones = mysqli_num_rows($resultPhones);

//first
 $i = 0; 
$phoneSelect = "<select>";
    while ($phone = mysqli_fetch_assoc($resultPhones)) { 
      $phoneSelect = $phoneSelect . "<option>{$phone[$i++]}</option>";
    }
   $phoneSelect = $phoneSelect . "</select>";

//second
    echo "<select>"; 
    while ($phone = mysqli_fetch_array($resultPhones)) {
      print_r ("<option>" . $phone[$i++] . "</option>");
    }
     echo "</select>";
  +-------------------------------------------------+
 |id | phone_1 | phone_2 | phone_3| phone_4| phone_4|
 |---+---------+---------+--------+--------+--------|
 |1  |  1      | 2       |  3     |  4     |  5     |
 |---+---------+---------+--------+--------+--------|
 |2  |  0      | 9       |  ---   |  ---   |  ---   |
 +---+----------------------------------------------+
 |3  |  1      | 2       |  3     |  4     |  5     |
 +---+----------------------------------------------+

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的问题,但我知道你想要创建每个ID中所有电话号码的下拉列表。

$query2 = 
    'SELECT
        `phone_1`, `phone_2`, 
        `phone_3`, `phone_4`, 
        `phone_5`
     FROM 
        phones_users';

$resultPhones = mysqli_query($con, $query2);

    while ($phone = mysqli_fetch_assoc($resultPhones)) { 
        $phoneSelect = '<select>';
        foreach ($phone as $key => $val) {
            if( preg_match( '#phone_\d+#', $key ))continue;//skip the non phone number
            $phoneSelect .= '<option>'.$val.'</option>';
        }
        $phoneSelect .= '</select>';
    }

无法测试,但我希望它能够接近xD