When articles talk about parameterized queries that stop SQL attacks, they don’t actually explain why, often this is the case “He does, so don’t ask why,” perhaps because they don’t know. A sure sign of a bad teacher is one who cannot admit that he knows nothing. But I was distracted. When I speak, I realized that it is completely clear that they simply confuse me. Imagine a dynamic SQL query
sqlQuery='SELECT * FROM custTable WHERE User=' + Username + ' AND Pass=' + password
so a simple sql injection was just to enter the username as "OR 1 = 1 - This will really make the sql query:
sqlQuery='SELECT * FROM custTable WHERE User='' OR 1=1
This suggests that all the clients they have are empty ('') or 1 = 1, which is logical, equating true. He then uses - to comment on the rest of the request. Thus, it will simply print the entire client table or do whatever you want with it, when you log in, it will log in with the rights of the first user, which can often be an administrator.
Now parameterized queries do it differently, with code like:
sqlQuery='SELECT * FROM custTable WHERE User=? AND Pass=?' parameters.add("User", username) parameters.add("Pass", password)
where username and password are variables pointing to the associated username and password entered
Now, perhaps you think this is not changing anything. Of course, you can still just enter something like Nobody OR 1 = 1 '- into the username field, effectively executing the query:
sqlQuery='SELECT * FROM custTable WHERE User=Nobody OR 1=1'-- AND Pass=?'
And that seems like a valid argument. But you are mistaken.
The way to work with parameterized queries is that sqlQuery is sent as a query, and the database knows exactly what this query will do, and only after that it will insert the username and passwords just as values. This means that they cannot complete the request because the database already knows what the request will do. Thus, in this case, he will look for the username "Nobody OR 1 = 1" - ") and an empty password, which should look false.
This is not a complete solution, and input validation still needs to be done, as it will not affect other issues such as XSS attacks, since you can still put javascript in the database. Then, if it is read on the page, it will display it as normal javascript, depending on some validation check. So the best thing is still to use input validation, but using parameterized queries or stored procedures to stop any SQL attacks.