Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping values in Rails (similar to mysql_real_escape_string())

I know about prepared statements, but if I'm using raw SQL, does ActiveRecord have a way to manually escape values?

Something like this would be nice:

self.escape("O'Malley") # O\'Malley 
like image 226
Jason Swett Avatar asked Jan 14 '11 21:01

Jason Swett


People also ask

What is the use of Mysql_real_escape_string () function?

The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection.

Does Mysql_real_escape_string prevent SQL injection?

mysql_real_escape_string ALONE can prevent nothing. Moreover, this function has nothing to do with injections at all. Whenever you need escaping, you need it despite of "security", but just because it is required by SQL syntax. And where you don't need it, escaping won't help you even a bit.

What is Mysql_escape_string?

mysql_escape_string is one of PHP mysql extension functions. It escapes a string provided as parameter for the function. Escapes means prepends backslash ( \ ) to special characters. mysql_escape_string is designed to be used with mysql_query function, to safely pass MySQL query parameters to the query.

How do I escape a string in MySQL?

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00 , \n , \r , \ , ' , " and \x1a . This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.


1 Answers

You can do:

Dude.sanitize("O'Malley") 

or

Dude.connection.quote("O'Malley") 

both with the same result: => "'O''Malley'"

like image 146
konus Avatar answered Sep 23 '22 11:09

konus