选中框是否正确?

时间:2017-11-29 03:44:34

标签: php arrays checkbox

我有PHP表格。此foreach执行多个checkedboxs。我想知道,用户选中了复选框C_ID INSERT到数据库。此代码无法正常工作。

    <?php
 if(isset($_POST['send'])){
      foreach($_POST['mod'] as $checkbox){
        $checkbox = $values[COURSE_ID];
        echo $checkbox . ' ';

        $date = date("Y-m-d"); 
        $sql= "INSERT INTO REG ( C_ID, REGISTERED, DATE) "
        . "VALUES ('".$values[C_ID]."', 'Y' ,'".$date. "')";
        DBQuery($sql);  
      } 
 }

echo "<form name=send method=post >";
   foreach($result1 as $value) {
    $checked = in_array($value, $selected) ? 'checked="checked"' : '';
    echo '<input type="checkbox" name="mod[]" value="' . $value[C_ID] .'"  ' . $checked . '>'. $value[TITLE] .'</input><br>';
   }
   echo "<button type=submit id=send name=send>send</button>";
   echo "</form>";
   ?>

2 个答案:

答案 0 :(得分:0)

试试这个:

 <?php
 $result1 = array(
    array(
        'C_ID' => 1,
        'TITLE' => "test"
    ),
    array(
        'C_ID' => 2,
        'TITLE' => "test 2"
    )
 );
 $selected = array();

if(isset($_POST['send'])){
      foreach($_POST['mod'] as $checkbox){
        $date = date("Y-m-d"); 
        echo $sql= "INSERT INTO REG ( C_ID, REGISTERED, DATE) "
        . "VALUES ('".$checkbox."', 'Y' ,'".$date. "')";
        DBQuery($sql);  
      } 
 }

echo "<form name=send method=post >";
   foreach($result1 as $value) {
    $checked = in_array($value, $selected) ? 'checked="checked"' : '';
    echo '<input type="checkbox" name="mod[]" value="' . $value['C_ID'] .'"  ' . $checked . '>'. $value['TITLE'] .'</input><br>';
   }
   echo "<button type=submit id=send name=send>send</button>";
   echo "</form>";
   ?>

答案 1 :(得分:0)

据我了解,此行错误 - $ checkbox = $ values [COURSE_ID];您正在通过变量覆盖复选框信息。我认为它应该是这样的 -

   <?php
    if(isset($_POST['send'])){
         foreach($_POST['mod'] as $checkbox){
           //$checkbox = $values[COURSE_ID];
           $courseId = $checkbox;
           echo $checkbox . ' ';

           $date = date("Y-m-d"); 
           $sql= "INSERT INTO REG ( C_ID, REGISTERED, DATE) "
           . "VALUES ('".$courseId."', 'Y' ,'".$date. "')";
           DBQuery($sql);  
         } 
    }

   echo "<form name=send method=post >";
      foreach($result1 as $value) {
       $checked = in_array($value, $selected) ? 'checked="checked"' : '';
       echo '<input type="checkbox" name="mod[]" value="' . $value[C_ID] .'"  ' . $checked . '>'. $value[TITLE] .'</input><br>';
      }
      echo "<button type=submit id=send name=send>send</button>";
      echo "</form>";

&GT;