如何使用序列化通过jquery和php保存多个复选框

时间:2013-09-04 22:45:47

标签: php jquery mysql

我想将多个复选框(PHP和JQuery)保存到MYSQL数据库中。示例表subscribefood有2个字段。列用户标识,食物。单击保存后,它将保存到那些表中;

我的jquery喜欢: -

function save_food_for_user(){

    var formData = $("#save-food").serialize();
    var ft_user_id = $('#ft_user_id').val();
    $.ajax({
        type: 'POST',
        url:  '<?php echo base_url(); ?>myaccount/saveFoodToUser/',
        data:{  formData,
                ft_user_id
             },
      dataType: "json",
        success: function(data){
            if(data.msg == "save"){ 
            alert('Done');
            }
        }
    });
}

php: -

<form action="" method="post" id="save-food"/>
            <?
            $counter=0;
            $sqlFoodType = mysql_query("select * from food_type");
            while ($rowFoodType = mysql_fetch_array($sqlFoodType))
            {
                $counter++;
                if($counter % 2 == 0){
                $class= "leftparentt";
                }else $class="rightparentt";
            ?>

            <div class="<?=$class?>">
            <input type="checkbox" id="foodtype" name="foodtype[]" value="<?=$rowFoodType['id'] ?>"  />&nbsp;&nbsp;<?=$rowFoodType['food_name'] ?>
            </div>
            <? } ?>
            </form>

    public function saveFoodToUser(){

        if(isset($_POST['save_food_for_user'])) {
        if(!empty($_POST['foodtype'])) {
            $ft_user_id = $_POST['ft_user_id'];
        $query = mysql_query("insert into subscribefood values ($ft_user_id,$foodtype)");
        $newData = array();
        $newData['msg'] = "save";
            }
        }

        }

1 个答案:

答案 0 :(得分:0)

public function saveFoodToUser(){
    if(isset($_POST['save_food_for_user'])) {
        if(!empty($_POST['foodtype'])) {
            $ft_user_id = $_POST['ft_user_id'];
            $values = array();

            //pair foods with user
            foreach($_POST['foodtype'] as $type_id){
                $values[] = "($ft_user_id, $type_id)";
            }
            $values = implode(',', $values);
            $query = mysql_query("insert into subscribefood values $values");
            $newData = array();
            $newData['msg'] = "save";

            //tell client that your data is saved.
            echo json_encode($newData);
        }
    }
}

试试这个