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");
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.
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.
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.
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.
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.
$value = Input::get("userID"); $results = DB::select( DB::raw("SELECT * FROM users WHERE users.id = :value"), array( 'value' => $value, ));
More Details HERE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With