如何将多个值/变量插入MySql数据库 [英] How To Insert Multiple Values / Variables To MySql Database

查看:101
本文介绍了如何将多个值/变量插入MySql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个票务预订系统,我想将数据插入数据库中.和往常一样,我使用HTML表单,所有数据都存储到数据库中.我想在数据库中插入多个座位号. (座位号=项目)

I am creating a Ticket Reservation System and I want to insert data into the Database. As usual, I used HTML form and all the data goes to the database. I want to insert multiple seat numbers into the database. ( Seat numbers = items )

但是,当我在SeatsController.php中使用此功能时,我只能插入一个座位号.

But , when I use this function in SeatsController.php , I am able to insert only one seat number.

public function seatsinsert(Request $request) {

    $date = $request->input('date');
    $st = $request->input('st');
    $item = $request->input('items');

    $user = new Seats();
    $user->date = $date;
    $user->st = $st;
    $user->item = $item;

    $this->validate($request, [
        'date' => 'required'
    ]);

    $user->save();

    $request->session()->flash('Msg', 'Successfully Inserted !!');

    return redirect('Seats');
}

然后我像下面那样更改SeatsController.php中的函数,以将多个席位号插入数据库.但是,现在我无法插入任何数据.在我的控制台中,它向我显示此错误-

Then I changed my function in SeatsController.php like below to insert multiple seat numbers into the database. But , now I can't insert any of the data. In my console , it shows me this error -

无法加载资源:服务器响应状态为500 (内部服务器错误).

Failed to load resource: the server responded with a status of 500 (Internal Server Error).

public function seatsinsert(Request $request)
    {

        $date = $request->input('date');
        $st = $request->input('st');
        $item = $request->input('items');
        //$item = item;

     $this->validate($request, [
            'date' => 'required'
        ]);   

    foreach($request->input("items") AS $item){
    $user = new Seats();
    $user->date = $date;
    $user->st = $st;
    $user->item = $item;

    $user->save();
}

            $request->session()->flash('Msg', 'Successfully Inserted !!');

            return redirect('Seats');

    }

如何解决此问题?

座椅结构图像

这是我的Seats.blade.php

Here is my Seats.blade.php

<form class="form-horizontal" id="form1" method="POST" action="{{ route('seatsinsert') }}" enctype="multipart/form-data">    

    {{ csrf_field() }}    

    <div class="dt"> <br>

        @if(session()->has('Msg'))
        <h4 class="alert alert-success"> {{ session()->get('Msg') }} </h4>
        @endif    

        <div class="form-group row">
            <label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
            <div class="col-10">
                <input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy" id="example-date-input">
            </div>
        </div>

        <div class="form-group">
            <label for="exampleSelect1">Select Time :</label>
            <select name="st" class="form-control" id="exampleSelect1">
                <option>10.30 am</option>
                <option>1.30 pm</option>
                <option>4.30 pm</option>
                <option>7.30 pm</option>
            </select>
        </div>  

    </div>

    <h2 style="font-size:1.2em;font-family: Times New Roman;"> Choose seats by clicking below seats :</h2>

    <div id="holder"> 
        <ul id="place">
        </ul>    
    </div>

    <input type="submit" class="btn btn-primary" id="btnShowNew" value="Continue"> <br><br>

    <script type="text/javascript">

        $(function () {

            $('#btnShowNew').click(function (e) {
e.preventDefault();

var items = [];
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
    items.push($(this).attr('title'));
});

    console.log(items);

   // $(location).attr('href', 'Seats');

    $.ajax({
    type: "post",
    url: "{{ route('seatsinsert') }}",
    data: {
        _token: "{{ csrf_token() }}",
        items: items,
        date: $('input[name=date]').val(),
        st: $('select[name=st]').val()
    }, success: function(data){
        $("form").trigger("reset");  
        $('#success_message').fadeIn().html("Text");  
    }

    });
});
        });

    </script>
</form>

这是我的路线.

Route::post('seatsinsert', [
    'uses' => 'SeatsController@seatsinsert',
    'as' => 'seatsinsert'
]);

这是Laravel错误日志

Here is Laravel Error Log

local.ERROR:为foreach()提供了无效的参数 {"exception":"[object](ErrorException(code:0):无效的参数 在以下位置为foreach()提供 D:\ wamp64 \ www \ FinalProject \ app \ Http \ Controllers \ SeatsController.php:28)

local.ERROR: Invalid argument supplied for foreach() {"exception":"[object] (ErrorException(code: 0): Invalid argument supplied for foreach() at D:\wamp64\www\FinalProject\app\Http\Controllers\SeatsController.php:28)

SeatsController.php:28是

SeatsController.php:28 is

foreach($ request-> input("items")AS $ item){

foreach($request->input("items") AS $item){

我用了dd($ request-> input('items'));然后单击提交按钮,则什么也没有发生.但是,当我从浏览器检查控制台时,会显示此错误-

I used dd($request->input('items')) ; and clicked submit button and nothing happens. But , when I check console from my browser it shows me this error -

POST http://localhost/FinalProject/public/seatsinsert 500 (Internal Server Error)

ajax @ jquery.min.js:19
(anonymous) @ Seats:442
handle @ jquery.min.js:19
(anonymous) @ jquery.min.js:19
jquery.min.js:19 XHR finished loading: POST "

推荐答案

问题将是通过ajax请求传递数组.要通过ajax传递数组,您必须JSON.stringify()数组.

The problem would be passing array through ajax request. To pass an array through ajax you have to JSON.stringify() your array.

$.ajax({
    type: "post",
    url: "{{ route('seatsinsert') }}",
    data: {
        _token: "{{ csrf_token() }}",
        items: JSON.stringify(items),
        date: $('input[name=date]').val(),
        st: $('select[name=st]').val()
    }, success: function(data){
        $("form").trigger("reset");  
        $('#success_message').fadeIn().html("Text");  
    }

});

在这种情况下,数组items被转换为json以通过ajax请求.

In this the array items are converted to json to pass through the ajax request.

还有一件事情,为了获得更好的体验,您不应该将sql查询放入循环中.

One more thing,for better experience you shouldn't put sql queries inside the loop.

这篇关于如何将多个值/变量插入MySql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆