从SQL查询中选择PHP中的正确单选按钮

时间:2014-11-18 16:42:48

标签: php mysql radio

我正在编写一些代码来编辑数据库中的数据。在原始表格(我模仿)上,它有一个单选按钮组,有6个选项:

 <label for="arrival">When will you arrive?</label><br />
    <input type="radio" id="pre" name="arrival" value="pre"/>Pre-KG<br />
    <input type="radio" id="wed" name="arrival" value="wed"/>Wednesday<br />
    <input type="radio" id="thu" name="arrival" value="thu"/>Thursday<br />
    <input type="radio" id="fri" name="arrival" value="fri"/>Friday<br />
    <input type="radio" id="sat" name="arrival" value="sat"/>Saturday<br />
    <input type="radio" id="sun" name="arrival" value="sun"/>Sunday<br />

我在提交表单后将值放到数据库中。现在我正在调用数据库中的数据,我希望选择正确的单选按钮。有什么建议吗?我似乎无法通过搜索找到它......

值使用$ row [“arrival”]从sql查询到我的数据库,其值为上述值之一...

以前我使用的是/否选项......

if ($row["costyn"]==1){
    echo '<input type="radio" name="costyn" value="1" checked>Yes<br>';
    echo '<input type="radio" name="costyn" value="0">No<br>';
    } else if ($row["costyn"]==0) {
    echo '<input type="radio" name="costyn" value="1" >Yes<br>';
    echo '<input type="radio" name="costyn" value="0" checked>No<br>';
    }

但必须有一个更清洁的方式。

2 个答案:

答案 0 :(得分:2)

在这种情况下,这样的事情可能会起作用:

<label for="arrival">When will you arrive?</label><br />
<?
$row["costyn"] = 4; // value from database

$radio_keys= array('pre', 'wed', 'thu', 'fri', 'sat', 'sun');
$radio_values = array('Pre-KG', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

foreach ($radio_keys as $key => $value) {
   echo '<input type="radio" name="arrival" value="'.$value.'" '.(($key+1)==$row["costyn"]?'checked':'').'/>'.$radio_values[$key].'<br />';
}
//ommited the ID, if you need it for JS/CSS reference you shall make it unique or use name/class for whole group.
?>

答案 1 :(得分:0)

你的PHP

首先获取您要检查的那个然后执行此操作

让我们说你有“前”

$radio = "pre";

然后

$checked[$radio] = "checked";

您的HTML

<label for="arrival">When will you arrive?</label><br />
<input type="radio" id="arrival1" name="arrival" value="pre" <?=(isset($checked['pre']))?$checked['pre']:"";>/>Pre-KG<br />
<input type="radio" id="arrival2" name="arrival" value="wed" <?=(isset($checked['wed']))?$checked['pre']:"";>/>Wednesday<br />
<input type="radio" id="arrival3" name="arrival" value="thu" <?=(isset($checked['thu']))?$checked['pre']:"";>/>Thursday<br />
<input type="radio" id="arrival4" name="arrival" value="fri" <?=(isset($checked['fri']))?$checked['pre']:"";>/>Friday<br />
<input type="radio" id="arrival5" name="arrival" value="sat" <?=(isset($checked['sat']))?$checked['pre']:"";>/>Saturday<br />
<input type="radio" id="arrival6" name="arrival" value="sun" <?=(isset($checked['sun']))?$checked['pre']:"";>/>Sunday<br />