如何使用sql表中的php创建下拉列表,并在下拉列表中显示动态默认表单值

时间:2019-03-29 22:09:34

标签: php html forms mysqli

我正在创建一个表单供用户更改有关成员的人口统计信息。我想用PHP以HTML形式提供一个下拉列表,并根据表中的值显示默认值。

示例:根据我们服务的邮政编码下拉列表更改成员的邮政编码(没有文本输入,只需从列表中选择),并默认显示成员的当前邮政编码分配。

<form>

<?php 
  // NOTE - geo meeting is equivalent to zipcodes
   $geo_locations = '<select name="geo1" id="geo1"> <option selected value="BAL"> Select new Location</option>';
     WHILE($row = mysqli_fetch_assoc($geomeetings))
                {
         $geo_locations .= ' <option value="'.$row['geo1'].'">'.$row['geoloc'].'</option>';
                }
         $geo_locations .= '</select>';
              echo '<TD>'.$geo_locations.'</TD>';
  // End of dropdown list of geo meeting locations -
?>

1 个答案:

答案 0 :(得分:0)

因此,您有$ geomeetings表,其中包含所有邮政编码。您还拥有另一个表-用户表-该表具有该用户的邮政编码。

即席且未经测试,但您知道了...

<?php 
    // NOTE - geo meeting is equivalent to zipcodes
    $user_geo_loc = '12345'; //This value comes from the user table
    $geo_locations = '
        <select name="geo1" id="geo1">
            <option value=""> Select new Location</option>
    ';
    while( $row = mysqli_fetch_assoc($geomeetings) ){
        $issel = '';
        if ($user_geo_loc == $row['geoloc']) $issel = ' selected';
        $geo_locations .= ' <option value="'.$row['geo1'].'" ' .$issel. '>'.$row['geoloc'].'</option>';
    }
    $geo_locations .= '</select>';
  // End of dropdown list of geo meeting locations -
?>

<form>
    <table>
        <tbody>
            <tr>
                <td>
                    Location: <?php echo $geo_locations; ?>
                </td>
            </tr>
        </tbody>
    </table>
</form>

请注意,该结构也可以替换为TERNARY运算符,如下所示:

$issel = ($user_geo_loc == $row['geoloc']) ? ' selected' : '';

(将显示为IF $user_geo == $row_geo THEN $issel = 'selected' ELSE $issel = ''