我正在为php / mysql应用程序中的数据创建更新表单。要从现有数据中预先填充更新表单中输入类型=“文本”字段的值,我使用此代码:
<label for="username">Username:</label>
<input name="username" type="text" value="<?php echo htmlentities($username, ENT_COMPAT, 'utf-8'); ?>">
上面的代码成功显示了数据库中的现有数据以进行编辑。 但是,对于动态创建选择选项的选择下拉输入字段,如下面的代码所示,如何在更新表单中重新显示现有选定数据?
<label for="user_role">User Role:</label>
<select name="user_role">
<option value="">Select User Role</option>
<?php
// get results
$query = 'SELECT userid, user_role FROM users_profile ORDER BY user_role';
$results = $conn->query($query);
while ($row = $results->fetch_assoc()) {?>
<option value="<?php echo $row['user_role']; ?>" <?php if (isset($_POST['userid']) && in_array($row['user_role'], $_POST['user_role'])) {echo 'selected';
} ?>><?php echo $row['user_role']; ?></option>
<?php } ?>
</select>
答案 0 :(得分:1)
试试这个
<label for="user_role">User Role:</label>
<select name="user_role">
<option value="">Select User Role</option>
<?php
// get results
$query = 'SELECT userid, user_role FROM users_profile ORDER BY user_role';
$results = $conn->query($query);
while ($row = $results->fetch_assoc()) {
$selected='';
if($row['user_role']==$update_id['user_role']) // put your update user_role here
$selected='selected="selected"';
?>
<option value="<?php echo $row['user_role']; ?>" <?php echo $selected; ?>><?php echo $row['user_role']; ?></option>
<?php } ?>
</select>