How to compile and execute a SQL query SAFELY?

u = Users.new #
x = ‘3; delete from users’ # user-supplied data, which is supposed to
be an integer
u.connection.execute(“select * from users where id = #{x}”) # deletes
ALL records

How would one guard against this SQL injection?

The best way I found so far is to use the quote method as follows:

u.connection.execute(“select * from users where id = #{u.quote x}”)

Is there a preferred/safer/better way?

-pachl

Users.find(x)

On 17/10/06, clintpachl [email protected] wrote:

u.connection.execute(“select * from users where id = #{u.quote x}”)

Is there a preferred/safer/better way?

-pachl

clintpachl <clintpachl@…> writes:

u = Users.new #
x = ‘3; delete from users’ # user-supplied data, which is supposed to
be an integer
u.connection.execute(“select * from users where id = #{x}”) # deletes
ALL records

How would one guard against this SQL injection?

In the case of an ID:

User.find(supposed_id)

otherwise ActiveRecord has a built-in way to escape SQL:

User.find(:all, :conditions => [“my_field = ?”, supposed_field])

See ActiveRecord::Base for
details

Gareth