gpt4 book ai didi

php - 如何预选表单中的下拉选项和复选框选项(PHP/MySQL)?

转载 作者:行者123 更新时间:2023-11-28 00:29:26 24 4
gpt4 key购买 nike

我正在创建一个更新表单,其中以前从 mysql 数据库提交的信息被抓取以填充当前表单。所以这就是我到目前为止所拥有的:

$select = mysql_query("SELECT * FROM some_table WHERE id = $id");
while ($return = mysql_fetch_assoc($select)) {
$name = $return['name'];
$bio = $return['bio'];
$maritalStatus = $return['marital_status'];
$favFood = $return['fav_food'];
}

<form action="page.php" method="post">
Name: <input type="text" name="name" value="<?php echo $name; ?>" /><br />

Bio: <textarea name="bio"><?php echo $bio; ?></textarea><br />

Marital Status
<select name="maritalStatus">
<option>Select One</option>
<option value="married">Married</option>
<option value="single">Single</option>
<option value="divorced">Divorced</option>
</select><br />

Favorite Food:
Cheeze: <input type="checkbox" name="favFood" value="cheeze" />
Cake: <input type="checkbox" name="favFood" value="cake" />
Oranges: <input type="checkbox" name="favFood" value="oranges" />
</form>

如您所见,我能够很好地显示通过输入文本框或文本区域输入的数据。但是,如果这两个选项是数据库中实际存在的选项,我该如何将“婚姻状况”下拉菜单预选为“离婚”选项并选中“最喜欢的食物”下的“橙子”复选框?

最佳答案

或者,为了避免向每个选项添加 if,只需执行以下操作:

echo '<select name="maritalStatus">';
$status = array("Select one", "Married", "Single", "Divorced");
foreach($status as $s)
{
$sel = ($maritalStatus == $s) ? 'selected = "selected"' : '';
echo '<option value="'.$s.'" '.$sel.'>'.$s.'</option>';
}
echo '</select>';

编辑:

要从数据库中动态填充选择,您可以:

echo '<select name="maritalStatus">';

$res = mysql_query("SELECT status FROM marital_status");
while ($row = mysql_fetch_array($res))
{
$s = $row['status']
$sel = ($maritalStatus == $s) ? 'selected = "selected"' : '';
echo '<option value="'.$s.'" '.$sel.'>'.$s.'</option>';
}
echo '</select>';

关于php - 如何预选表单中的下拉选项和复选框选项(PHP/MySQL)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3079468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com