han*_*gee 2 html php mysql html-select
我有一个简单的库存数据库,在input_data表单中,其中一个输入字段是字段,如下所示:
<select>
<option>In Inventory</option>
<option>In Process</option>
<option>Shipped/in-transit</option>
<option>Received by recipient</option>
</select>
Run Code Online (Sandbox Code Playgroud)
例如,如果我使用"正在处理"输入数据,之后我想更新该数据.我的update_page.php文件中的默认值返回"In Inventory".我想看到选中的"In Process"值.
以下是来自我的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>
Run Code Online (Sandbox Code Playgroud)
选择在HTML中没有值属性 - 您可以选择多个选项,这由选项元素上的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>
Run Code Online (Sandbox Code Playgroud)
稍微好一点的方法:
<?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>
Run Code Online (Sandbox Code Playgroud)
最好的方法 - 将这些选项存储在数据库表中 - 可能更好地使用ID值而不是字符串(允许更容易更新选项标签),并循环使用上面的数据库查询中的可能选项.如果经常使用此选择列表,请缓存查询结果以获取选项(请记住,如果列表更新,则需要清除缓存)