如何将数组的多个复选框值插入数据库

时间:2019-05-16 06:37:59

标签: php html

我对如何插入复选框的多个数组数据感到困惑。我遇到了一些代码,但是我不知道如何在我的php代码中实现它们。如何从数据库中的复选框插入多个数据?有人能帮我吗?对此,我真的非常感激。预先谢谢你。

html代码:

 <?php
include ('connect.php');

 $sql2 = "SELECT * FROM owner WHERE owner_username ='".$_SESSION['username']."'";
$result2 = mysqli_query($conn,$sql2);
$row = mysqli_fetch_array($result2);
$id = $row['owner_id'];

$sql = "SELECT cat_id,name,gender,health_status,neutered,breed,color,age
 FROM cat WHERE owner_fk = '$id'";

$result = $conn-> query($sql);

if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {

    echo "<tr>";
    echo "<td>" .$row ['name']. "</td>";
    echo "<td>" .$row ['gender']. "</td>";
    echo "<td>" .$row ['health_status']. "</td>";
    echo "<td>" .$row ['neutered']. "</td>";
    echo "<td>" .$row ['breed']. "</td>";
    echo "<td>" .$row ['color']. "</td>";
    echo "<td>" .$row ['age']. "</td>";
    echo "<td>" ."<input type='checkbox'  name= 'check[]' value=''". " 
    </td>";
    echo "</tr>";
    }
      echo "</table>";
    }
    else{

    echo "0 result";
    }
     $conn-> close();
     ?>

这是我的php代码:

  <?php

  include ('connect.php');

  if(isset($_POST['submit']))
  {
for($i=0;$i<count($_POST["check"]);$i++)
   }

     $p_id =$_GET ['sitter'];
     $price = $_POST ['price'];
     $pickup_date =$_POST ['pickup_date'];
     $dropoff_date =$_POST ['dropoff_date'];
     $numdays = $_POST ['numdays'];
     $total =$_POST ['test'];

    $sql2 = "INSERT INTO cat_sitter(sitter_fk,cat_fk, price, date_in, 
    date_out,total_day, total)VALUES ('$p_id','".$_POST["check"] 
    [$i]."','$cat_id','$price','$pickup_date','$dropoff_date','$numdays', 
    '$total')" or die ("Error inserting data into table");

    if ($conn->query($sql2) === TRUE) {
echo "<script language='javascript'>alert('Succesfully Book.')
    window.location.replace(\"book_page.php\");
</script>";
}else{
echo "error: " . $sql2 . "<br>" . $conn->error;
    }
    ?>

2 个答案:

答案 0 :(得分:0)

使用爆破功能

In your case replace $_POST["check"] with implode(',',$_POST["check"]) then it will work fine fine hope so

答案 1 :(得分:0)

而不是爆炸和爆炸。您可以使用将复选框数组转换为JSON并存储在单个字段中。

 // Convert Array to JSON String
 $checkArray = $_POST["check"];
 $checkJSON = json_encode($checkArray);

从数据库中获取其值后,将JSON转换为数组。

 // Convert JSON string to Array
 //$checkJSON is variable fetched from database 
 $checkArray = json_decode($checkJSON, true);
 print_r($checkArray);        // Dump all data of the Array
相关问题