lundi 8 mai 2017

Insert Checkbox Array into Multiple MySQL table Columns with PHP

I am pretty stumped, I thought this would work for sure. I want to insert multiple checkbox values (if selected) into different columns of one table. I was attempting to do this with a for loop and keeping the naming convention consistent so I could utilize the for loop with the checkbox array. Here is php code:

$connection = new mysqli("localhost","root","","employee_db");
if(isset($_POST['check'])){
    $check = $_POST['check'];
    if($check){
        print_r($check);
    }else{
        echo "nothing checked";
    }

    for($i=0;$i<sizeof($check);$i++){
        $query = "INSERT INTO  `checklist_test` (`$check[$i]`) VALUE (`\"$check[$i]\"`)"; 
        $result = mysqli_query($connection,$query);
        if(!$result){
            die("NOPE <br>" . mysqli_error($connection));
        }else{
            echo "yup";
        }
    }
}

And here is the HTML

<form action="" method="post>
  <input type="checkbox" name="check[]" value="check1">Check1
  <input type="checkbox" name="check[]" value="check2">Check2
  <input type="checkbox" name="check[]" value="check3">Check3
  <input type="submit" value="submit">
</form>

The MySQL Columns are "id, check1, check2, check3" so SQL should look like:

INSERT INTO `checklist_test` (`id`, `check1`, `check2`, `check3`) 
VALUES (NULL, 'test', 'test', 'test');

Appreciater outside P.O.V. that I need thanks!




Aucun commentaire:

Enregistrer un commentaire