我想将多个复选框选中的选项保存到MySQL中

时间:2013-06-05 19:41:49

标签: php mysql

我搜索了很多,但没有找到任何解决方案。我想在SQL中保存复选框选中的选项。如果用户选择了两个复选框,则必须用逗号分隔保存在MySQL中。

Kinly请帮我解决这个问题

HTML CODE

<input name="patno" id="patno">
<input type="checkbox" name="newt[]" value="Diesel" id="type" />Diesel
<input type="checkbox" name="newt[]" value="Petrol" id="type" />Petrol
<input type="checkbox" name="newt[]" value="Electricity" id="type" />Electricity

PHP代码     

$order = "INSERT INTO tblsampo
            (patno, stno, newt)
            VALUES
            ('$smonth',
            '$patno','$stno','$newt')";

$result = mysql_query($order);  //order executes
if($result){
    echo("<br>Input data is succeed");
} else{
    echo("<br>Input data is fail");
}
?>

3 个答案:

答案 0 :(得分:1)

简单地破坏$ _POST ['type']数组就像这样......

$types = implode(",", $_POST['type']);

然后将$ types变量插入表格中......

因此...

$types = implode(",", $_POST['type']);

if($types){
$order = "INSERT INTO tblsampo
        (patno, stno, type)
        VALUES
        ('$smonth',
        '$patno','$stno','$types')";}

答案 1 :(得分:1)

试试这个

$types = implode(',',$_POST['type']);
$sql = "INSERT INTO tblsampo
        (patno, stno, type)
        VALUES
        ('$smonth',
        '$patno','$stno','$types')";
mysql_query($sql)

答案 2 :(得分:0)

尝试以下方法:

$newt = false;
if (isset($_POST['newt']) && !empty($_POST['newt']) && is_array($_POST['newt'])){
   $newt = implode(",", $_POST['newt']);
}

然后只需运行您的查询,但检查 $ myTypes 是否 false

if ($newt) {
  //YOUR QUERY. TIP: use PDO or MySQLi instead of MySQL_* functions
}