如何使多个复选框与PHP和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 THAT WORKS for this question

processing code :

$salesman = $data['data-invoice-salesman']; // this is an array
                $salesman_array = array(); // create new array
                $salesman_names = array(1 => "User1",2 => "User2",3 => "User3",4 => "User4",5 => "User");
                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[$salesman_names[$i]] = "checked";
                } else {
                    $salesman_array[$salesman_names[$i]] = "";
                }
                }
                $salesman_json = mysqli_real_escape_string($this->_con, json_encode($salesman_array)); // encode the array into JSON and then escape it.

form code THAT WORKS :

<?php
        $salesmand = json_decode($invoice['Invoice']['salesman'], true);
        $salesman_names = array(1 => "User1",2 => "User2",3 => "User3",4 => "User4",5 => "User5");
            foreach ($salesman_names AS $i => $name) {
                if ($salesman[$name] == "checked") {
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$name.'<br>';
                } else {
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" /> '.$name.'<br>';
                }
            }
        ?>
            </div>  

Add an array that maps the indexes to the name:

$salesman_names = array(
    1 => "Joe Smith",
    2 => "Fred Flintston",
    3 => "George Jetson",
    4 => "John Hamm",
    5 => "Alan Smithee"
);

Then in your loop, you can do:

$salesman_array[$salesan_names[$i]] = "checked";

The JSON that's saved in the database might then look like:

{"Joe Smith":"checked", "Fred Flintson": "", "George Jetson","checked", "John Hamm":"", "Alan Smithee":""}

To display the checkboxes, you would refer to the $salesman_array when displaying it:

$salesman = json_decode($invoice['Invoice']['salesman'], true);
foreach ($salesman_names AS $i => $name) {
    if ($salesman[$name] == "checked") {
        echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$name.'<br>';
    } else {
        echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" /> '.$name.'<br>';
    }
}