Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape raw SQL queries in Laravel 4

How does one go about escaping parameters passed to a raw query in Laravel 4? I expected something like DB::escape() (which rings a bell from Laravel 3) and also attempted DB::quote() (which I thought could be available through the PDO object)

$query = DB::select("SELECT * FROM users WHERE users.id = " . DB::escape($userId)); 

We can't use the select method with placeholders as the above is just a simplified example of what we are trying to achieve. We have a large custom query with a few nested select queries that cannot be adapted to the query builder.

What is the best approach to escaping something prior to inserting in Laravel 4?

EDIT:

I've just discovered that you can access the PDO object and use the quote function on it this way. Is this still the best approach, or is there an easier way to access this function?

DB::connection()->getPdo()->quote("string to quote"); 
like image 776
Dwight Avatar asked Sep 23 '13 02:09

Dwight


People also ask

What is DB :: Raw in Laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. Check this ref. link, with more details: http://fideloper.com/laravel-raw-queries.

How use raw queries in Laravel?

Example from Laravel documentation: $users = DB::table('users') ->selectRaw('count(*) as user_count, status') ->where('status', '<>', 1) ->groupBy('status') ->get(); Another example: $products = DB::table('products') ->leftjoin('category','category.

What is WhereRaw in Laravel?

WhereRaw() is a function of Laravel query builder which puts your input as it is in the SQL query's where clause. Think of it as the where() function whose input argument will not be processed before inserting into queries.

What is a raw query in SQL?

Raw SQL, sometimes also called native SQL, is the most basic, most low-level form of database interaction. You tell the database what to do in the language of the database. Most developers should know basics of SQL. This means how to CREATE tables and views, how to SELECT and JOIN data, how to UPDATE and DELETE data.


2 Answers

You can quote your strings this way, through the DB facade.

DB::connection()->getPdo()->quote("string to quote"); 

I did put this answer in my question when I discovered it, however I've now put it in as an actual answer to make it easier for others to find.

like image 179
Dwight Avatar answered Oct 03 '22 08:10

Dwight


$value = Input::get("userID");  $results = DB::select( DB::raw("SELECT * FROM users WHERE users.id = :value"), array(    'value' => $value,  )); 

More Details HERE

like image 32
Arun Kumar M Avatar answered Oct 03 '22 06:10

Arun Kumar M