如何在数据库中插入多个复选框值?这是我的代码,它适用于只有一个值的单选按钮,但如果我有复选框,如何插入更多?
PHP代码:
if(isset($_POST['radio']) &&
isset($_POST['checkbox'])){
$radio = $_POST['radio'];
$checkbox= $_POST['checkbox'];
$sql = "INSERT INTO info(radio, checkbox)VALUES ('$radio', '$checkbox')";
$result = mysql_query($sql);
}
HTML CODE:
<input type="radio" name="radio" value="1">1<br>
<input type="radio" name="radio" value="2">2<br>
<input type="checkbox" name="checkbox" value="1">1<br>
<input type="checkbox" name="checkbox" value="2">2<br>
<input type="checkbox" name="checkbox" value="3">3<br>
<input type="checkbox" name="checkbox" value="4">4<br>
<input type="checkbox" name="checkbox" value="5">5<br>
<input type="checkbox" name="checkbox" value="6">6<br>
答案 0 :(得分:2)
HTML
<input type="radio" name="radio" value="1">1<br>
<input type="radio" name="radio" value="2">2<br>
<input type="checkbox" name="checkbox[]" value="1">1<br>
<input type="checkbox" name="checkbox[]" value="2">2<br>
<input type="checkbox" name="checkbox[]" value="3">3<br>
<input type="checkbox" name="checkbox[]" value="4">4<br>
<input type="checkbox" name="checkbox[]" value="5">5<br>
<input type="checkbox" name="checkbox[]" value="6">6<br>
腓
使用foreach获取复选框的所有值
//Do the necessary coding and then
if(!empty($_POST['checkbox']))
foreach($_POST['checkbox'] as $key=>$value){
if(trim($value) != ''){
//Do insertion here
}
}
}
答案 1 :(得分:0)
使用php核心函数serialize()
和unserialize()
答案 2 :(得分:0)
将您的姓名复选框更改为:
<input type="checkbox" name="checkbox[]" value="1">1<br>
<input type="checkbox" name="checkbox[]" value="2">2<br>
<input type="checkbox" name="checkbox[]" value="3">3<br>
<input type="checkbox" name="checkbox[]" value="4">4<br>
<input type="checkbox" name="checkbox[]" value="5">5<br>
<input type="checkbox" name="checkbox[]" value="6">6<br>
php上的做到了:
$radio = $_POST['radio'];
$sql = 'INSERT INTO info(radio, checkbox)';
foreach($_POST['checkbox'] as $item){
$sql .= "VALUES('$radio', '$item')," ;
}
$sql = trim($sql, ','); //remove the last ',';
//performe all insert at once.
避免使用mysql_ *函数,请尝试PDO