2014-01-05 176 views
0

我有这个HTML/PHP代码列出选择元素中的选项。选择正确从MySQL数据库中选择选项

请告诉我做出了正确的选择最好的方式来选择基于从MySQL数据库中的记录:

这工作得很好,但没有任何简单的方法用一行代码做到这一点,而不是,如果这样做的每个选项的声明?

<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> 

回答

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>"; 
0

您可能希望把这些值在数据库中,或者如果你想avoit它,只是把它们放到一个数组,并使用循环打印的所有选项并标记为正确的一个。

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有一个更好的答案。