我的问题是如何从PHP中的数据库中检索复选框值。以下代码无效。
C<E<P
答案 0 :(得分:4)
更改声明,
$focus=explode(",",$row['hobby']);
要:
$hobby=explode(",",$row['hobby']);
此外,您可以使用三元运算符而不是像以下那样最小化代码:
<td>
<input type="checkbox" name="hobby[]" value="Cricket" size="17" <?php echo (in_array("Cricket",$hobby)) ? 'checked="checked" : '';?>>Cricket
<input type="checkbox" name="hobby[]" value="Music" size="17" <?php echo (in_array("Music",$hobby)) ? 'checked="checked" : '';?>>Music
<input type="checkbox" name="hobby[]" value="Reading" size="17" <?php echo (in_array("Reading",$hobby)) ? 'checked="checked" : '';?>>Reading
</td>
另外,@ mapek建议,你的SQL将获取所有记录。
$result = mysqli_query($con,"SELECT hobby FROM simple WHERE id = id");
由于id
始终等于id
。
您应将其更改为:
$result = mysqli_query($con,"SELECT hobby FROM simple WHERE id = '$id'");
使用数组最小化此代码的另一个版本:
<td>
<?php
$hobbies = array('Cricket', 'Music', 'Reading');
if (! empty($hobbies)) {
foreach ($hobbies as $myHobby) {
$checked = (in_array($myHobby, $hobby)) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="hobby[]" value="<?php echo $myHobby;?>" size="17" <?php echo $checked;?>><?php echo $myHobby;?>
<?php
}
}
?>
</td>
答案 1 :(得分:2)
试试这个:需要进行许多更改
<td>Hobby</td>
<?php
$id= 1; // your input id value
$result = mysql_query("SELECT hobby FROM simple WHERE id = $id");
while($row = mysql_fetch_array($result))
{
$hobby=explode(",",$row['hobby']);
?>
<td><input type="checkbox" name="hobby[]" value="Cricket" size="17" <?php if(in_array("Cricket",$hobby)) echo 'checked="checked"'; ?> >Cricket
<input type="checkbox" name="hobby[]" value="Music" size="17" <?php if(in_array("Music",$hobby)) echo 'checked="checked"'; ?> >Music
<input type="checkbox" name="hobby[]" value="Reading" size="17" <?php if(in_array("Reading",$hobby)) echo 'checked="checked"'; ?> >Reading
<input type="checkbox" name="hobby[]" value="Study" size="17" <?php if(in_array("Study",$hobby)) echo 'checked="checked"'; ?> >Study</td>
<?php
}
?>
</tr>
答案 2 :(得分:1)
在
中更改变量名称 <iframe src="http://www.google.com"></iframe>
从<?php if(in_array("Cricket",$hobby)) { ?>
到$hobby
答案 3 :(得分:0)
$newArray = explode(",",$result['hobbies']);
<input type="checkbox" name ="hobbies[]" value ="reading" <?php if(in_array("reading",$newArray)){ echo "checked";} ?>
<input type="checkbox" name ="hobbies[]" value = "games" <?php if(in_array("games",$newArray)){ echo "checked";}?>>`
<input type="checkbox" name ="hobbies[]" value = "coding" <?php if(in_array("coding",$newArray)){ echo "checked";} ?>