SilverStripe: Escape raw values for a SQL query
Posted August 9th, 2010 in Quick Tips and SilverStripe
This is just quick little post for self reference to show how to escape values which go into a raw SQL query in SilverStripe; I find myself never being able to remember this and having to always look it up.
Escape a value using convert::raw2sql
When using DB::query, DataObject::get and DataObject::get_one with filters, etc in SilverStripe you may need to include variables which have come from user input. As with all database queries these values need to be escaped to a) prevent SQL injection and b) to ensure there are no quer errors.
In SilverStripe use the following to escape the variable so it is safe to put into the query:
convert::raw2sql($value)
So for example, to put it into a query using DB::query:
DB::query("DELETE FROM Foo WHERE Bar = " . convert::raw2sql($somevalue));

Comments
blog comments powered by Disqus