如何通过从数据库中读取值来选择单选按钮


How do I make a radio button selected by reading the value from my database?

我有一个带有一些单选按钮、一个文本字段和一个文本区域的表单,我将其插入到我的数据库中。现在我可以选择编辑整个内容。当我单击按钮编辑时,我再次获得表单,并且文本字段和文本区域中的值与我插入到数据库中的值相同。现在我不知道如何获得具有正确值的单选按钮作为检查数据库中的值。

这是我的表格:

<<<EOT
            <table>
  <form action="index.php?page=artikelen_bewerken_verwijderen&id={$_GET['id']}" method="post"> 
  <tr><th><td><input type="text" size="108%" name="title" value="{$titel}"></td></tr></th> 
  <tr><th><td> <textarea name="description"  rows="20" cols="80" >{$nieuwsbericht}</textarea></td></tr></th>
  <tr><th><td><input type="radio" name="club"  value="borussia-dortmund">Borussia Dortmund </td></tr></th>
  <tr><th><td><input type="radio" name="club"  value="ajax">Ajax</td></tr></th>
  <tr><th><td><input type="radio" name="club" value="ac-milan">AC Milan</td></tr></th>
  <tr><th><td><input type="radio" name="club"  value="fc-bayern">Bayern Munchen</td></tr></th>
  <tr><th><td><input type="radio" name="club"  value="feyenoord">Feyenoord</td></tr></th>
  <tr><th><td><input type="radio" name="club" value="juventus">Juventus</td></tr></th>
  <tr><th><td><input type="radio" name="club"  value="real-madrid">Real Madrid</td></tr></th>
  <tr><th><td><input type="radio" name="club"  value="fc-barcelona">Barcelona</td></tr></th>   
  <tr><th><td><input name="edit" type="submit" value="Edit"></td></tr></th> 
  </form> 
 </table>
EOT;

有谁知道如何像我想要的那样检查单选按钮?

最好的方法是将整个事情编译成一个json数组,然后让javascript来做这件事。

如果只能选择一个单选按钮:

var radio_checked = '<?php echo $row['club']; ?>';
$(document).ready(function() { // start this when site is fully loaded
    if (radio_checked) { // check if variable is empty or not
        $(':radio[value='+radio_checked+']').prop('checked', true);
    }
});

或者,如果选中了多个单选按钮(我假设您将结果转换为 PHP 中的数组):

var radio_array = <?php echo json_encode($yourArray); ?>;   
$(document).ready(function() { // start this when site is fully loaded
    if(!$.isArray(radio_array) || !radio_array.length) { // check if array is empty or not
        for (index in radio_array) {
            $(':radio[value='+radio_array[index]+']').prop('checked', true);
        }
    }
});

如果你不想用jQuery,有一种纯粹的PHP方式,但这每次都需要编码:

<input type="radio" name="club" <?php echo ($row['club'] == 'borussia-dortmund')? 'checked' : ''; ?> value="borussia-dortmund">
<input type="radio" name="club" <?php echo ($row['club'] == 'ajax')? 'checked' : ''; ?> value="ajax">

我希望这有所帮助。

从数据库中获取值,并将其与单选按钮的值进行交叉检查。如果匹配,请向收音机添加"选中"属性。

<input type="radio" name="club" value="borussia-dortmund" <?= ($valueFromDatabase == 'borussia-dortmund') ? 'checked' : ''?>>

假设你的MySQL结果数组是: $row,假设你的单选按钮索引是:radio,现在$row['radio']它是你的单选按钮从数据库中读取,放置选中或未选中的条件

如下
<input type="radio" <?php if($row['radio']==1){?> 'checked' <?php } ?>/>
Let me know if you want more..