jeudi 31 décembre 2015

How to make multiple checkboxes work with php and sql

How would I pass an array of multiple checkboxes and values through php, saving to a sql database, as well as being able to pull up the saved data back on the client side?

For example, I have an array that saves checkbox values in the way of '"checked"""checked""""', but not only do I want to save the checked value, I also want to save the form data, as follows :

  • Apples : Checked
  • Oranges : Not Checked
  • Bananas : Checked
  • Tomatoes : Checked

Any help would be GREATLY appreciated, please answer with context of how to do, not just code - still learning!

Here is the code I have so far :

(index page)

    <?php
                $salesman = json_decode($invoice['Invoice']['salesman'], true);
                    if(empty($salesman)){
                    for($i = 1; $i <= 5; $i++){
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>';
                    }
                    } else {
                    foreach($salesman as $k => $v){
                    $i = $k+1;
                    if($v == "checked") {
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$i.'<br>'; // if checked, check.
                    } else {
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>'; // if not checked, don't check.
                    }
                }
            }
            ?>

(php page)

$salesman = $data['data-invoice-salesman']; // this is an array
                $salesman_array = array(); // create new array
                for($i = 1; $i <= 5; $i++){ // loop from 1 to 5
                if(in_array($i, $salesman)){ // if value exists (has been selected), stack 'checked', if not, stack ''.
                    $salesman_array[] = "checked";
                } else {
                    $salesman_array[] = "";
                }
                }
                $salesman_json = mysqli_real_escape_string($this->_con, json_encode($salesman_array)); // encode the array into JSON and then escape it.




Aucun commentaire:

Enregistrer un commentaire