php 打钩实现
复选框基础实现
使用HTML的<input type="checkbox">元素创建复选框。PHP通过$_POST或$_GET获取选中状态:
<form method="post">
<input type="checkbox" name="agree" value="1"> 我同意协议
<input type="submit" value="提交">
</form>
PHP处理代码:
if(isset($_POST['agree']) && $_POST['agree'] == '1') {
echo "复选框已选中";
} else {
echo "未同意协议";
}
多选框组处理
多个复选框使用数组形式命名:
<input type="checkbox" name="interests[]" value="sports"> 体育
<input type="checkbox" name="interests[]" value="music"> 音乐
PHP接收处理:

$selected = $_POST['interests'] ?? [];
foreach($selected as $interest) {
echo "已选择: $interest<br>";
}
数据库存储方案
将复选框状态存储到MySQL数据库:
// 连接数据库后
$agreed = isset($_POST['agree']) ? 1 : 0;
$stmt = $pdo->prepare("INSERT INTO users (agreed) VALUES (?)");
$stmt->execute([$agreed]);
动态选中状态
根据数据库值回显选中状态:

$checked = $user['agreed'] ? 'checked' : '';
echo "<input type='checkbox' name='agree' value='1' $checked>";
AJAX异步提交
使用jQuery实现无刷新提交:
$('input[type=checkbox]').change(function(){
$.post('save.php', {
checked: this.checked ? 1 : 0
});
});
样式美化方案
使用CSS自定义复选框样式:
input[type="checkbox"] {
appearance: none;
width: 20px;
height: 20px;
border: 2px solid #ccc;
}
input[type="checkbox"]:checked {
background-color: #2196F3;
}
表单验证要求
确保必选复选框被选中:
if(empty($_POST['mandatory_check'])) {
$errors[] = "必须同意条款";
}