如何在数据库中存储多个复选框数据

时间:2019-05-18 06:03:43

标签: database checkbox

我正在尝试在数据库中插入多个复选框数据,但是有一点问题。当我尝试插入复选框数据时,它仅插入id而没有其他内容。 这是我的完整代码:-

<?php 
include("config.php");

if(isset($_POST['save'])){

  $contact_sms = $_POST['contact_sms'];  
  $check[] = $_POST['check'];
  $firm_name = $_POST['firm_name'];
  var_dump($firm_name);
  $checkbox = $_POST['check'];

  for($i=0;$i<count($checkbox);$i++){
    $bulksms="INSERT INTO bulk_sms (sent_sms,firmname_sms,contact_sms) VALUES('".$checkbox[$i]. "','".$row['firm_name']. "','$contact_sms')";
    $smsquery=mysqli_query($conn, $bulksms);
  }
}

$sql="SELECT * FROM inventory_details where status ='0' AND role='0' ORDER BY position ASC, role ASC, visiter DESC limit 0,100";  
$query=mysqli_query($conn, $sql);


?>

    <form method="post" action="" id="msform">   
      <?php
        $i=0;
        while($row=mysqli_fetch_assoc($query)){
        $id = $row['id'];
        $firm_name = $row['firm_name'];
      ?>  

        <div class="col-md-4">
          <input type="text" class="form-control" name="id_sms" value="<?php echo $id;?>">
        </div>
        <div class="col-md-6">
          <input type="text" class="form-control" name="firm_name[]" value="<?php echo $firm_name;?>">
        </div>
        <div class="col-md-2">
          <input type="checkbox" id="checkItem" name="check[]" value="<?php echo "$id"; ?>">
        </div>

      <?php
        $i++;
        }
      ?>

      <input type="text" class="form-control" name="contact_sms" placeholder="Contact Number.."> 
      <button type="submit" class="btn btn-success" name="save">Send</button>
    </form>

当我单击“发送”按钮时,它仅将id存储在字段sent_sms中,而在字段firm_name中则什么也不存储。请帮帮我。我很难被困住。

更新的代码:

if(isset($_POST['save'])){

  $contact_sms = $_POST['contact_sms'];  
  $check[] = $_POST['check'];
  $firm_name = $_POST['firm_name'];
  var_dump($_POST);
  $checkbox = $_POST['check'];

  for($i=0;$i<count($checkbox);$i++){
    $bulksms="INSERT INTO bulk_sms (sent_sms,firmname_sms,contact_sms) VALUES('".$checkbox[$i]. "','".$firm_name[$i]. "','$contact_sms')";
    $smsquery=mysqli_query($conn, $bulksms);
  }
}

1 个答案:

答案 0 :(得分:0)

我认为$row['firm_name']未定义,请尝试更改此行:

$bulksms="INSERT INTO bulk_sms (sent_sms,firmname_sms,contact_sms) VALUES('".$checkbox[$i]. "','".$row['firm_name']. "','$contact_sms')";

对此:

$bulksms="INSERT INTO bulk_sms (sent_sms,firmname_sms,contact_sms) VALUES('".$checkbox[$i]. "','".$firm_name. "','$contact_sms')";

还应注意,您尚未清理输入内容,从而使站点容易受到sql注入的攻击。您应该始终清理用户输入,强烈建议在插入数据库时​​使用准备好的语句。