php在我的sql数据库中为每个选中的复选框插入多行

时间:2013-08-21 09:47:54

标签: php mysql

说我有以下表格:

<form action="" method="post">
</BR>
<?php
// create two dropdowns with ajax
echo "<font id=\"categoria\"><select>\n";
echo "<option value='0'>Select the Firm</option> \n" ;
echo "</select></font>\n";
?>
<?php
echo "<font id=\"subcategoria\"><select>\n";
echo "<option value='0'>Select the Claims Hub</option> \n" ;
echo "</select></font>\n";
?>

<form method="post" align= "right">
<table >

    <tr><td>&nbsp;</td>
    <tr>
         <td style="text-align: left; ">Criminal  </td>
         <td align="left" >
            <input type="checkbox" name="mattertype" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
    <tr>
         <td style="text-align: left; ">Labour  </td>
         <td align="left" >
            <input type="checkbox" name="mattertype" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
    <tr>
         <td style="text-align: left; ">Civil  </td>
         <td align="left" >
            <input type="checkbox" name="mattertype" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
     <tr>
         <td style="text-align: left; ">Active  </td>
         <td align="left" >
            <input type="checkbox" name="active" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
    <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="submit" value="Add" align= "right" /></td>
    </tr>

</table>

如何编写php代码以将以下信息作为所有选中复选框的新记录插入?例如,我检查过Civil,Labor和Active。我现在想要第一个必须插入的记录来阅读

公司区域Mattertype Active(我的sql表)

子类别的属性值Civl 1
子类别劳动1的分类价值

如果选中任何或所有民事,劳工或刑事复选框,则必须插入categoria的值,subcatgoria的值,首先勾选的复选框(mattertype),如果激活则勾选,则为1激活。

然后对于第二个记录,再次使用categoria的值,subcatgoria的值,第二个勾选的复选框(mattertype),如果激活则勾选,则为1激活。

等等。我希望这是有道理的。

3 个答案:

答案 0 :(得分:1)

首先更改mattertype复选框以使用数组作为值,并将值更改为每个值的唯一值(1表示犯罪,2表示劳动,3表示民事)

<input type="checkbox" name="mattertype[]" value="1" />
<input type="checkbox" name="mattertype[]" value="2" />
<input type="checkbox" name="mattertype[]" value="3" />

PHP

$categoria = $_POST['categoria'];
$subcategoria = $_POST['subcategoria'];
$mattertypes = $_POST['mattertype'];
$active = $_POST['active'] == 1 ? 1 : 0;

//$matertypes will be an array so loop over it
foreach( $mattertypes as $type ) {
  switch( $type ) {
     case '1':
       $typename = "Criminal";
     break;
     case '2':
       $typename = "Labour";
     break;
     case '3':
       $typename = "Civil";
     break;
  }
  $SQL = "INSERT into mytable (categoria,subcategoria,mattertype,active) VALUES('$categoria','$subcategoria','$typename','$active')";

  //Do the call to database with the query.
}

当然,在将数据放入数据库之前对其进行清理。

答案 1 :(得分:0)

in html

  <input type="checkbox" name="mattertype[]" value="1" />
php中的

//get mattertype which are checked by

$_POST['mattertype'];// this is come as array then use according to your requirement

答案 2 :(得分:0)

将复选框名称设为name="mattertype[]"并更改值。

然后发布为$_POST['mattertype'];