PHP MySql:选中动态单选框


PHP MySql: Checked Dynamic radio Box

我有动态选中单选框的代码:

PHP:

if ($author === 0) {$checked = 'checked';} else {$checked == '';}
if ($author === 1) {$checked = 'checked';} else {$checked == '';}
if ($author === 2) {$checked = 'checked';} else {$checked == '';}
HTML:

<input type="radio" name="test" <?PHP echo $checked; ?> />
<input type="radio" name="test" <?PHP echo $checked; ?> />
<input type="radio" name="test" <?PHP echo $checked; ?> />

这是真的吗?什么是更好的/优化的方式?

我可以写任何PHP函数或类保存代码和选中任何单选框吗?

如果您期望使用缩短的if语句形式,可以节省一些行和不必要的额外变量。第一个input的示例:

<input type="radio" name="test" <?php echo $author === 0 ? 'checked' : '' ?> />

理想情况下,如果author值与该输入相关,则需要检查按钮,例如:

<input type="radio" name="test" value="0" <?php echo ($author == 0 ? 'checked="checked"' : ''); ?> />
<input type="radio" name="test" value="1" <?php echo ($author == 1 ? 'checked="checked"' : ''); ?> />
<input type="radio" name="test" value="2" <?php echo ($author == 2 ? 'checked="checked"' : ''); ?> />

如果值为any,您当前正在检查所有。

HTML标记错误。有了HTML,用户就可以选择所有的无线电。要使用户只能从那组选项中选择一个单选按钮,请将名称更改为all match,如下所示:

<input type="radio" name="test1" <?PHP echo $checked; ?> />
<input type="radio" name="test1" <?PHP echo $checked; ?> />
<input type="radio" name="test1" <?PHP echo $checked; ?> />

你可以做的事情:

<?php
    $checked = ($author >= 0 && $author <= 2 ? 'checked' : '');
?>
HTML

<input type="radio" name="test" <?php echo $checked; ?> />
<input type="radio" name="test1" <?php echo $checked; ?> />
<input type="radio" name="test2" <?php echo $checked; ?> />
<?php
    switch($author) {
        case 0:
        case 1:
        case 2:
             $checked = "checked";
             break;
        default:
             $checked = '';
    }