在"用户设置"我的页面的标签,我希望用户确定来自特定用户的帖子类型。这是表格:
<form method="post" action="" name="permitted_categories">
Select or deselect which types of Posts that you would like to see.
<p>
<?
$cat_query = mysqli_query($con, "SELECT permitcat FROM permitted WHERE username='$userLoggedIn' AND friendname='$username'")
?>
<label>
<input type="checkbox" name="categories[]" value="Life" id="Life" <? echo $checked;?>>
Life</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Politics" id="Politics" <? echo $checked;?>>
Politics</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Entertainment" id="Entertainment" <? echo $checked;?>>
Entertainment</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Food" id="Food" <? echo $checked;?>>
Food</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <? echo $checked;?>>
Business/Financial</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Fitness" id="Fitness" <? echo $checked;?>>
Fitness/Health</label>
<br>
<input type="submit" name="update_categories" id="update_categories">
<?
if(isset($_POST['update_categories'])) {
$permitted_categories = $_POST['categories'];
echo "You will only see the following categories from ". $profile_user_obj->getFirstAndLastName() .": ";
foreach ($permitted_categories as $permcat){
echo $permcat .", ";
}
$values = implode(", ", $permitted_categories);
$permit_query = mysqli_query($con, "INSERT INTO permitted (id, username, friendname, permitcat) VALUES('','$userLoggedIn', '$username', '$values')");
} ?>
</p>
</form>
我要做的是自动检查在数组中找到相应值的方框。
我尝试了几件事,但无法让代码工作。
答案 0 :(得分:1)
这很简单。
HTML文档:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
如果您在输入标签的末尾写“已选中”,则会检查此信息,如字所示;)
另一件事,不要混合标签:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
<label>Life</label>
最后,如果你在开头做这个,你的代码将会起作用:
$checked = 'checked';
但这会检查所有方框,你需要检查一下,如下:
<?php $checked = 'checked'; ?>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <?php echo if($something == $otherThing) echo $checked;?> >
答案 1 :(得分:1)
<input type="checkbox" name="categories[]" value="Life" id="Life" <?php if($something) { echo "checked"; }?>>
这可能因阵列内容而异 这里有一些例子
$assoc_array = [
"life" => "yes",
"food" => "no",
];
if($assoc_array['life'] == "yes"){ echo "checked"; }
$array = [
"life",
"food"
];
if (in_array("food", $array)) {
echo "checked";
}
$assoc_array_bool = [
"life" => "whatever",
"food" => "whatever"
];
if($assoc_array_bool['life']){ echo "checked"; }
// would not check the checkbox
// if you replaced $assoc_array_bool['life'] with $assoc_array_bool['sport']