将默认值设置为单选按钮php

时间:2016-03-15 23:11:02

标签: php html

我想为表单的单选按钮设置默认值。默认值应与数据库中的值匹配。我知道如何使用checked =" checked"来设置我的默认值。在我的情况下,问题在于如何在radiobuttons中使用数据库值作为默认值。

<tr>
    <td>ASP.NET</td>
    <td><input type="radio" name="asp" value="not at all competent" ></td>
    <td><input type="radio" name="asp" value="little competent" ></td>
    <td><input type="radio" name="asp" value="moderately competent"</td>
    <td><input type="radio" name="asp" value="extremely competent"></td>
</tr>

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

<?php
//Retrieve your value here

$query="select * from technical_skills where student_id='$student_id'";
$result=mysqli_query($conn,$query); 
$row=mysqli_fetch_array($result); 
// Assign the column to the variable
$dbValue = $row['columnname'];
?>
<tr>
    <td>ASP.NET</td>
    <td><input type="radio" name="asp" value="not at all competent"<?php echo ($dbValue=='not at all competent'?' checked=checked':''); ?> ></td>
    <td><input type="radio" name="asp" value="little competent"<?php echo ($dbValue=='little competent'?' checked=checked':''); ?> ></td>
    <td><input type="radio" name="asp" value="moderately competent"<?php echo ($dbValue=='moderately competent'?' checked=checked':''); ?> ></td>
    <td><input type="radio" name="asp" value="extremely competent"<?php echo ($dbValue=='extremely competent'?' checked=checked':''); ?> ></td>
</tr>

答案 1 :(得分:-1)

您可以为每个选项定义一个空变量,并将它们设置为&#39; checked = checked&#39;根据DB返回的值。

示例:

$not_competent = ''
if($dbResult == 'not_competent') $not_competent = 'checked=checked';

对其他选项执行相同操作,然后打印表格。

  

在&#34; ...&#34;之间写表。所以PHP可以解析变量并显示   正确的信息

print "<tr>
    <td>ASP.NET</td>
    <td><input type='radio' name='asp' value='not at all competent' $not_competent></td>
    <td><input type='radio' name='asp' value='little competent' $little competent></td>
    <td><input type='radio' name='asp' value='moderately competent' $moderately_competent></td>
    <td><input type='radio' name='asp' value='extremely competent' $extremely_competent></td>
</tr>";

干杯!