从MySQL数据库中选择正确的选择选项

时间:2014-01-05 19:22:20

标签: php mysql

我有这个HTML / PHP代码,它列出了select元素中的选项。

根据MySQL数据库中的记录选择正确选项的最佳方法是什么:

这样可以正常工作,但是有没有更简单的方法来使用一行代码而不是每个选项执行if语句?

<select name="status" id="status">
            <option value="Open"<?php if($ticket["status"]=="Open"){echo('selected="selected"');}?>>Open</option>
            <option value="Needs Action"<?php if($ticket["status"]=="Needs Action"){echo('selected="selected"');}?>>Needs Action</option>
            <option value="Customer Reply"<?php if($ticket["status"]=="Customer Reply"){echo('selected="selected"');}?>>Customer Reply</option>
            <option value="Completed"<?php if($ticket["status"]=="Completed"){echo('selected="selected"');}?>>Completed</option>
          </select>

3 个答案:

答案 0 :(得分:1)

使用数组:

echo "<select name='status' id='status'>";
$statuses = array('Open', 'Needs Action', 'Customer Reply', 'Completed');
foreach ($statuses as $status) {
    echo "<option value='$status' " . ($ticket['status'] == $status) ? "selected='selected'" : "" . "/>";
}
echo "</select>";

答案 1 :(得分:0)

您可能希望将这些值放在数据库中,或者如果您想避免它,只需将它们放入一个数组中并使用循环打印所有选项并将其标记为正确选择。

答案 2 :(得分:0)

是的,代码可以更短(并且更具可读性):

if($ticket["status"]=="Open") {
    $openSelected = "selected='selected'";
}
if($ticket["status"]=="Needs Action") {
    $needsActionSelected = "selected='selected'";
}
if($ticket["status"]=="Customer Reply") {
    $customerReplySelected = "selected='selected'";
}
if($ticket["status"]=="Completed") {
    $completedSelected = "selected='selected'";
}

<select name="status" id="status">
            <option value="Open" <?php print($openSelected) ?>>Open</option>
            <option value="Needs Action"<?php print($needsActionSelected) ?>>Needs Action</option>
            <option value="Customer Reply"<?php print($customerReplySelected) ?>>Customer Reply</option>
            <option value="Completed"<?php print($completedSelected) ?>>Completed</option>
          </select>

编辑// @Barmar有更好的答案。