如何将laravel与mySQL

时间:2018-11-21 21:05:17

标签: php mysql laravel

我已经阅读了一些教程和视频。我刚刚下载并安装了laravel。试图创建一个简单的注册表格。

welcome.blade.php

<form action="{{URL::to('/store')}}" method="post">
       {{csrf_field()}}
       <input type="text" name="clientFirstname" >
       <input type="text" name="clientSurname" >
       <input type="text" name="clientEmail">
       <input type="hidden" name="token" value="">
       <button type="submit" name="button">add</button>
</form>

web.php

Route::view('/', 'welcome');
Route::post('/store', "Controller@store");

Controller.php

class Controller extends BaseController {

    public function store(Request $request) {
        //print_r ($request->input());
        //print_r ($request->input('clientFirstname'));
        $result=DB::insert("INSERT INTO test('firstname', 'surname', 'email') VALUES(?, ?, ?)", $request->input('clientFirstname'), $request->input('clientSurname'), $request->input('clientEmail'));
        echo $result;
    }
}

.env

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testdb
DB_USERNAME=root
DB_PASSWORD=

database.php

        'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'testdb'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
        ],

我已经通过phpmyadmin创建了一个名为testdb的数据库。让我通知您,我可以打印表单字段,但是当我将上述插入代码插入数据库时​​,出现以下错误。

  

Symfony \组件\调试\异常\ FatalThrowableError   (E_RECOVERABLE_ERROR)类型错误:参数1传递给   Illuminate \ Database \ Connection :: prepareBindings()必须为以下类型   数组,给定字符串,调用   C:\ Users \ regor \ ExampleProject \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection.php   在第665行

我将不胜感激。 :)

1 个答案:

答案 0 :(得分:2)

DB::insert()方法接受一个数组作为第二个参数。

您应该这样使用它:

DB::insert("INSERT INTO test(`firstname`, `surname`, `email`) VALUES(?, ?, ?)", [
    $request->input('clientFirstname'),
    $request->input('clientSurname'),
    $request->input('clientEmail')
]);

此外,对列标识符使用反斜线代替单引号。