如何避免sql注入?

时间:2012-12-17 03:33:10

标签: mysql ruby-on-rails sql-injection

我正在进行查询:

    @results = RubyGem.where(
    'name LIKE ?', "%#{searchphrase}%"
    ).paginate(
        :page => params[:page], 
        :per_page => 50, 
        :group => "name", 
        :order => [
            "CASE WHEN name like '#{searchphrase}%' THEN 0 
            WHEN name like '% %#{searchphrase}% %' THEN 1 
            WHEN name like '%#{searchphrase}' THEN 2 
            ELSE 3 END, name"
        ]
    )

但是我很确定这很容易受到注射......有人可以解决这个问题,所以它不是这样,同时保持功能相同吗?我正在使用Ruby on Rails和MySQL。

1 个答案:

答案 0 :(得分:2)

@results = RubyGem.where(
    'name LIKE ?', "%#{searchphrase}%"
).paginate(
     :page => params[:page], 
     :per_page => 50, 
     :group => "name", 
     :order => [
       "CASE WHEN name like ? THEN 0 WHEN name like  THEN 1 WHEN name like '%#{searchphrase}' THEN 2 ELSE 3 END, name", "#{searchphrase}%", "% %#{searchphrase}% %"
     ]
)