0

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

我的 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";
            }
        }

        }
4

1 回答 1

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);
        }
    }
}

尝试这个

于 2013-09-04T23:16:18.363 回答