i have manage to insert my checkbox array data into database. the problem is when i check multiple checkbox only the first data in array is inserted in database. i need when i check multiple checkbox, all the data i have check insert into database.can someone help me?

this is my php code:


    include ('connect.php');

 $cat = implode(',', $_POST['check']);


    for($i=0; $i<count($cat);$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','" . $cat[$i] . "','$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.')

    echo "error: " . $sql2 . "<br>" . $conn->error;

this is my html code:

      include ('connect.php');

   $sql = "SELECT cat_id,name,gender,health_status,neutered,breed,color,age FROM cat WHERE owner_fk = '$id'";
  $result3 = mysqli_query($conn,$sql);
  $row6 = mysqli_fetch_array($result3);
  $cato = $row6['cat_id'];
  $result = $conn-> query($sql);

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

        //table code//

       echo "<td>" ."<input type='checkbox'  name= 'check[]' value='$cato'". "</td>";
       echo "</tr>";
       echo "</table>";
     echo "0 result";
      $conn-> close();


In your HTML code <table> not opened, table row <tr> not opened, invalid <input> tag without > - it should be something like

if($result->num_rows > 0){
    echo '<table>';
    while ($row6 = $result->fetch_assoc()){
        //table code//
        echo '<tr>';
        echo '<td><input type="checkbox"  name="check[]" value="'.$cato.'" /></td>';
        echo '</tr>';
    echo '</table>';

PHP code $cat better use filtered variable

$cat = filter_input(

other variables also filtered eg

$price = filter_input(INPUT_POST,'price',FILTER_SANITIZE_STRING);
$pickup_date = filter_input(INPUT_POST,'pickup_date',FILTER_SANITIZE_STRING);

Do not pass user input variables direct to SQL query - its a potential SQL injection risk! Use prepared statement instead - prepare, bind_param, execute - read manual MySQLi bind param or PDO bind param

commented: thanks for responding, really appreciate it. :) +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.