I'm learning about RoR/databases and this topic particularly confused me. In the book Agile Development with Rails 4 , they give an example of finding a list of all orders with for an entry with name Dave:
pos = Order.where("name = 'Dave' and pay_type = 'po")
The book goes on to say that you would never want to do something like this:
name = params[:name]
pos = Order.where("name = '#{name}'and pay_type = 'po'")
Instead you should do this:
name = params[:name]
pos = Order.where(["name = ? and pay_type = 'po'",name])
I understand, what SQL injection is as a concept but there are a few particulars that confuse me. For starters, how exactly does the SQL injection work as a syntax.
I get that the danger is that someone can drop a table/database if you interpolate an outside form parameter like the first example but how?
Lets say you had this:
name = params[:name] #DROP DATABASE database_name
pos = Order.where("name = '#{DROP DATABASE database_name}'and pay_type = 'po'")
Is this how SQL injection works? SQL is a syntax, there should be no field in the database where "name = DROP DATABASE database_name", wouldn't this return an error instead of dropping the database?
Also, how would the question mark version protect against this. Again, let's say you have this scenario.
name = params[:name] #DROP DATABASE database_name
pos = Order.where(["name = ? and pay_type = 'po'", DROP DATABASE database_name])
Won't this replace the question mark with the DROP DATABASE database_name syntax and then wouldn't we have the same problem that we had in the first example? How exactly is this protecting an application against SQL? I searched for a few tutorials on http://hub.tutsplus.com/ and searched on Google, but I don't get the concept behind it. Any help?