Skip to content
Minute Campus.

Almost rightLesson 041 min

This login query can be rewritten by the user

A login that builds its SQL query by gluing in the user's text can be rewritten by that user. A password containing a quote mark closes the text early, and the rest becomes part of the query: the password matches, or one equals one. Since one always equals one, the login passes. This is SQL injection. The fix is a parameterised query, where values travel separately as data.

Remember

Never build a query by joining strings; pass values as parameters.

Transcript

The lesson, word for word.

Read it at your own pace, or search the page for a term.

This login query can be rewritten by the user. Three seconds: which line lets them? The code checks a name and password against a database. It builds the query by gluing the user's text into a line of SQL. Type a normal password, and it works. Now type a password that contains a quote mark and a few words of SQL. The quote closes the text early, and the rest becomes part of the query itself. The query now says: the password matches, or one equals one. One always equals one. So the database returns a user, and the login passes with the wrong password. This is SQL injection, one of the oldest attacks on the web. The fix is a parameterised query. You write question marks where the values go, and pass the values separately. The database treats them as data, never as commands. The rule: never build a query by joining strings.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.