itchyspacesuit itchyspacesuit - 1 year ago 74
MySQL Question

Is there a good ruby parallel to the php mysql_real_escape_string ()

I'm currently working on a project that has ruby at one end with a mysql database and a php presentation on another side. I'd really like to be able to push content to the db with ruby and then pull it out with php. The content is json encoded right now, but I'd like to be able to escape the strings the same way at both ends so that I'm not getting stuck with a bunch of artifacts.

Any suggestions would be really appreciated.

Answer Source

The answer in Ruby is to avoid using the low-level driver like mysql2 and instead use a database layer like Sequel or ActiveRecord which comes bundled with Rails.

Sequel is the most no-nonsense option of these two and it allows you to write statements with placeholder values:

INSERT INTO my_table (name, on_date) VALUES (?,?)

That way your data is added after the fact using bindings and escaping is handled for you automatically. This is the safest way to do it.

If you do need to do manual escaping, do it in a way that's as obvious as possible since getting this wrong can expose you to huge risks.

PHP has a terrible reputation for taking a cavalier approach to writing database calls. Ruby's approach, like that in the Python world, is much more orderly and encourages the use of higher-level abstractions when writing database code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download