Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape for MYSQL queries from Ruby on Rails?

When searching the MYSQL database for a Rails 2.3.14 app, I need to escape the search string appropriately so I can search for strings containing single-quotes (apostrophes). What's the best way to do this? I'm using the mysql gem, in case that matters.

like image 423
joanwolk Avatar asked Jul 20 '12 14:07

joanwolk


1 Answers

Rails quotes strings as follows:

# Quotes a string, escaping any ' (single quote) and \ (backslash) characters.
def quote_string(s)
  s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
end
like image 165
JJD Avatar answered Sep 30 '22 23:09

JJD