如何在 Laravel 5.2 中使用准备好的语句

Fra*_*oxx 1 php mysql laravel-5.2

我在 Laravel 5.2 中像这样创建了一个简单的插入语句。

User::create([
        'email' => $request->input('email'),
        'username' => $request->input('username'),
        'password' => bcrypt($request->input('password')),
    ]);
Run Code Online (Sandbox Code Playgroud)

但我希望我的数据库更安全,所以我更喜欢使用 Prepared Statement。我要求正确编写语法?如何正确散列我的password内语句?

User::insert('insert into users (email, username, password) values (?,?,?)');
Run Code Online (Sandbox Code Playgroud)

Sas*_*vic 5

Eloquent 在幕后为你做这件事,在完成所有花哨的事情之后,最后,Eloquent 调用PDO::prepare()PDO::bindValue()最后PDO::execute();.

仔细阅读 的代码Illuminate\Database\Connection以了解其要点。

您唯一需要注意的是不要使用DB::raw()直接提供的用户输入,例如:

// This is bad
DB::raw('SELECT * FROM table_name WHERE col = '.$request->query('col'));

// This is good
DB::raw('SELECT * FROM table_name WHERE col = ?', [$request->query('col')]);
//or
DB::raw('SELECT * FROM table_name WHERE col = :col', ['col' => $request->query('col')]);
Run Code Online (Sandbox Code Playgroud)

  • 我认为你的意思是“DB::select”而不是“DB::raw”,后者返回一个 SQL 表达式,并且它没有用于绑定的第二个参数,但前者执行该语句。https://github.com/Illuminate/database/blob/5.2/Connection.php#L284 其他一切都很好! (2认同)