开发者

how to insert an hidden field value along side with a checkbox in to the database

i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:

  <?php

 include('db.php');

 $sql = "select * from sheet1 order by course_level asc";
 $r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
  type= "checkbox"    value   =    "'.$row['course_code'].'">'.$row['course_code'].'
</td>       <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
 </td><input   type=hidden    name=cid[] value="'.$row['cid'].'">
 </tr>';

  }

 ?>

And this is the action code:

    <?php
   include('db.php');
  if(isset($_POST['courses']))
   echo 'lie';
   else
  echo 'true开发者_如何学JAVA';
  foreach($_POST['courses'] as $row=>$id){

  $courses=$id;
  $cid = $_POST['cid'][$row];
  $sql = "insert into selected_courses values ('','$courses','$cid')";
  $r = mysqli_query($dbc,$sql);
  }
  if($r)
  echo 'done';
  ?>

thanks a lot.


You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).

I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this

<input type="checkbox"
       name="courses[]"
       value="<?php echo htmlspecialchars($row['cid']) ?>">

Then your INSERT query simply becomes

// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
    $stmt->execute();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜