A Simple SQLi Example

Let's look at how SQLi breaks down into actual code.

Take a look at the following query, where the value of $id would be input supplied by the user:

SELECT title, author FROM posts WHERE id=$id

One common SQLi technique is to input data that can change the context or logic of the SQL statement's execution. Because that $id value is being inserted directly—with no data sanitization, removal of dangerous code, or data type transformation—the SQL statement is dynamic, and subject to tampering.

Let's make a change that will affect the execution of the statement:

SELECT title, author FROM posts WHERE id=10 OR 1=1

In this case, 10 OR 1=1 is the user-supplied data. By modifying the WHERE clause, the user can alter the logic of the developer-supplied part of the executed example. The preceding example is pretty innocuous, but if the statement asked for account information from a user table, or a part of the database associated with privileges, instead of just information about a blog post, that could represent a way to seriously damage the application.