php 如何获取复选框的多个值,并且不被覆盖
首先:html复选框表单 ,name='hobby[]'; 这样添加的是数组,能添加无数个.[] [] []很重要
<div> <p>爱好:</p> <span> 英雄联盟:<input type="checkbox" name="hobby[]" value="英雄联盟" id=""> 王者荣耀:<input type="checkbox" name="hobby[]" value="王者荣耀" id="" > 刀塔:<input type="checkbox" name="hobby[]" value="刀塔" id="" > </span> </div>
再来 php获取表单部分:使用implode()函数,把数组转变成字符串,然后存进数据库.就可以了
$hobby = $_POST['hobby']; $hobby_do = implode(',',$hobby); var_dump($hobby_do);exit;
提交前.
提交后.
完整代码:
<?php include 'public.php'; if(isset($_POST['token']) && $_POST['token'] == '令牌号码' && !empty($_POST['name'])) { $name = $_POST['name']; $hobby = $_POST['hobby']; $hobby_do = implode(',',$hobby); var_dump($hobby_do);exit; $sql = "insert into hobby values(null,'$name','$hobby_do')"; if(mysqli_query($conn,$sql)){ echo '插入成功id为'.mysqli_insert_id($conn).'的数据'; }else{ echo '没有数据'; } }else{ echo '非法提交'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>添加学生信息</title> <style> .adds-stu-wrap{ width: 700px; height: auto; margin: 0 auto; margin-top: 100px; } .adds-stu{ float: left; width: 100%; height: auto; background-color: #eee; padding: 15px 10px; } .adds-stu div{ float: left; width: 100%; margin-bottom: 20px; } .adds-stu div>p{ float: left; width: 100px; margin: 0 10px 0 0; text-align: right; } .adds-stu div>input{ float: left; width: 260px; } </style> </head> <body> <div class="adds-stu-wrap"> <h2 class="head" style="text-align:center">添加学生信息</h2> <div class="adds-stu"> <form action="" method="post"> <div> <p>姓名:</p> <input type="text" name="name" id=""> </div> <div> <p>爱好:</p> <span> 英雄联盟:<input type="checkbox" name="hobby[]" value="英雄联盟" id=""> 王者荣耀:<input type="checkbox" name="hobby[]" value="王者荣耀" id="" > 刀塔:<input type="checkbox" name="hobby[]" value="刀塔" id="" > </span> </div> <div> <button >提交</button> <input type="hidden" name="token" value="令牌号码"> </div> </form> </div> </div> </body> </html>