addslashes

  • This function’s solution will only work within the context of the Rails framework.

    This should NOT be used to escape values being inserted into the database. This function is generally deprecated in favor of either the mysql_real_escape_string function or bind variables in PHP.

    PHP

    // don't do this!
    $name = addslashes("O'malley");
    mysql_query("SELECT * FROM users WHERE name='$name'");

    To escape variables in Rails, we’ll use replacement variables.

    Rails

    name = "O'malley"
    User.find(:all, :conditions => ["name = ?", name])

    If you need to escape characters in a string (but are not using this to escape data for the database) this can be done in Ruby with substitution on the ('), ("), and (\0) characters using String#gsub.

    PHP

    $string = addslashes("I can't imagine \"that\"!\0");
    var_export($string);
    // => 'I can\\\'t imagine \\"that\\"!\\0'

    Ruby

    p "I can't imagine \"that\"!\0".gsub(/('|"|\0)/, "\\\\\\1")
    # => "I can\\'t imagine \\\"that\\\"!\\\000"

    Note that PHP’s var_export dumps with apostrophes (“single quotes”) while Ruby’s p dumps with quotes. Despite this difference in appearance, the results are equivalent.

    see also

array

Looking for Rails or PHP web application development, integration, and training?

Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.