将复选框对应的数量插入数据库

时间:2018-03-18 02:37:42

标签: php mysql checkbox product-quantity

我的表单中有多个复选框,此人需要输入所选项目类型的数量。现在,我的问题是我无法将数据插入数据库。

这是我的add_record.php代码:

<?php  
include("connect.php");
include("header.php");
$sql_student = "SELECT * FROM student";
$result_student = mysql_query($sql_student); 
 ?> 

<form method="post" id="add_form" action="add_record.php">
 <label>Name</label>
    <input placeholder="Enter Student Name" type="text" name="name" id="name" class="form-control" />
    <br />
    <input placeholder="Enter Student ID" type="text" name="stud_id" id="stud_id" class="form-control" />
    <br />
    <?php 
       $sql_baggage = "SELECT * FROM baggage";
       $result_baggage = mysql_query($sql_baggage);
    ?>
    <label>Bag Types</label></br>
    <table style="border:none;">
    <?php while($row_bag = mysql_fetch_array($result_baggage))
    {
       $baggage_id = $row_bag['baggage_id'];
    ?>
    <tr>
        <td><?php echo $row_bag['baggage_id'];?>
        <td><?php echo $row_bag['baggage_type'];?></td>
        <td><input type="checkbox" name="tick[]" value="<?php echo $baggage_id;?>"/></td>
        <td><input type="text" size="2" name="txt[<?php echo $baggage_id;?>]" placeholder=" "></td>
    <?php
    ?></td></tr>
    </table>
    <br />
    <input type="submit" name="submit" id="submit" value="Add Record" class="btn btn-success btn-secondary pull-right" />
</form>
<?php
if(isset($_POST['submit']))
{
   $name = $_POST["name"]; 
   $stud_id = $_POST["stud_id"];    
   $stu_query = "INSERT INTO student(student_id,student_name) VALUES ('$stud_id','$name')";

   if(mysql_query($stu_query))
   {
      if(!empty($_POST['tick']))
      {
        foreach($_POST['tick'] as $selected)
        {
          $qty = $_POST['txt'][$selected];
          $inv_query = "INSERT INTO inventory (invstu_id,invbag_id,invbag_quantity) VALUES 
          ('$stud_id','$selected', '$qty')";

          if(mysql_query($inv_query))
          {
            echo'<script>alert("A record has been inserted!")</script>';
          }
          else
          {
            echo "Database error";
          }
        } 
      }
      else
      {
        echo'<script>alert("A record has been inserted!")</script>';
      }
  }
}
?>
</body>
</html>

我知道数据是通过foreach函数传递的,因为当我勾选两个复选框时,我得到数据库错误的回显两次。但是,该值未插入数据库。

1 个答案:

答案 0 :(得分:0)

最后通过回显mysql_error()来解决问题,代码没有任何问题。在数据库中只是有点问题。谢谢!