我有一个简单的库存数据库,在 input_data 表单上,其中一个输入字段是 field,如下所示:
<select>
<option>In Inventory</option>
<option>In Process</option>
<option>Shipped/in-transit</option>
<option>Received by recipient</option>
</select>
例如,如果我输入一个带有“处理中”的数据,稍后我想更新该特定数据。在我的 update_page.php 文件中默认回到“In Inventory”。我希望看到选中的“处理中”值。
这是我的 update_page.php 中的非工作代码片段:
<select name="status" value="<?php echo $row['status']; ?>">
<option>In Inventory</option>
<option>In Process</option>
<option>Shipped/in-transit</option>
<option>Received by recipient</option>
</select>
最佳答案
Select 在 HTML 中没有 value 属性——您可以选择多个选项,这由 option 元素上的 selected 属性决定
肮脏的方式:
<select name="status">
<option<?php if ($row['status'] == "In Inventory"): ?> selected="selected"<?php endif; ?>>In Inventory</option>
<option<?php if ($row['status'] == "In Process"): ?> selected="selected"<?php endif; ?>>In Process</option>
<option<?php if ($row['status'] == "Shipped/in-transit"): ?> selected="selected"<?php endif; ?>>Shipped/in-transit</option>
<option<?php if ($row['status'] == "Received by recipient"): ?> selected="selected"<?php endif; ?>>Received by recipient</option>
</select>
稍微好一点的方法:
<?php
$options = array("In Inventory", "In Process", "Shipped/in-transit", "Received by recipient");
?>
<select>
<?php foreach ($options as $option): ?>
<option value="<?php echo $option; ?>"<?php if ($row['status'] == $option): ?> selected="selected"<?php endif; ?>>
<?php echo $option; ?>
</option>
<?php endforeach; ?>
</select>
最佳方法 - 将这些选项存储在数据库表中 - 使用 ID 值而不是字符串可能更好(允许更轻松地更新选项标签)并像我上面那样循环从数据库查询中获取的可能选项。如果经常使用此选择列表,请缓存查询结果以获取选项(请记住,如果列表更新,您需要清除缓存)
关于php - HTML <Select> <Option> 默认根据MySQL数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076292/