如何使多个复选框与php和sql一起工作


How to make multiple checkboxes work with php and sql

如何通过php传递一个由多个复选框和值组成的数组,保存到sql数据库中,并能够在客户端取回保存的数据?

例如,我有一个数组,它以"checked"check"""的方式保存复选框值,但我不仅想保存选中的值,还想保存表单数据,如下所示:

  • 苹果:已选中
  • 橙子:未选中
  • 香蕉:已检查
  • 番茄:勾选

任何帮助都将不胜感激,请回答如何做,而不仅仅是代码-仍在学习!

以下是适用于此问题的代码

处理代码:

$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.

有效的表单代码:

<?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>  

添加一个数组,将索引映射到名称:

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

然后在你的循环中,你可以做:

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

保存在数据库中的JSON可能看起来像:

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

要显示复选框,在显示时可以参考$salesman_array

$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>';
    }
}