8

I'd like to use the following query for my Rails 4 application but am concerned about SQL injection attacks:

@persons = People.where("persons.name LIKE ?", "%#{params[:search]}%")

Can somebody show me the safe way to write the above statement? I've tried the following but am not sure if it is SQL-injection-proof:

search = "%" + params[:search] + "%"
@persons = People.where("persons.name LIKE ?", search)

Thanks!

2 Answers 2

12

Your examples are fine, as zishe said.

Whenever you use question marks to a method and pass another parameters as the search query, it sanitizes your query string.

It is dangerous when you manually do string concatenations to create your query, for example:

Project.where("name = '#{params[:name]}'")

Click here for more information

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @Migore! I appreciate the additional resource as well as the explanation as to why my examples are SQL injection-proof!
9

Both your statements will be safe. Also you can write it like this:

@persons = People.where("persons.name LIKE concat('%', ?, '%')", params[:search])

Simlilar qestion

2 Comments

No, the pattern must be a string. You don't have the SQL string in quotes. But you must not put the placeholder inside a SQL string. This would work: "persons.name LIKE CONCAT('%', ?, '%')"
@zishe - thanks for answering my question as well as providing a more concise piece of code. I'm accepting Migore's response since he provided some additional information as to why my examples were not vulnerable to SQL injection. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.