Prevent SQL injection for queries that combine the query builder with DB::raw()

前端 未结 2 1501
失恋的感觉
失恋的感觉 2021-01-12 03:38

In Laravel 4, I want to protect some complex database queries from SQL injection. These queries use a combination of the query builder and DB::raw(). Here is a simplified ex

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 04:19

    I discovered the query builder has a method called setBindings() that can be useful in this instance:

    $field = 'email';
    $id = 1;
    $user = DB::table('users')->select(DB::raw(":field as foo"))
            ->addSelect('email')
            ->whereId(DB::raw(":id"))
            ->setBindings(['field' => $field, 'id' => $id])
            ->get();
    

提交回复
热议问题