How SQL Injection Works

Constructing a database query is a perfectly straightforward process. It typically proceeds something like this (for demonstration purposes, we'll assume that you have a database of wines, in which one of the fields is the grape variety):

  1. You provide a form that allows the user to submit something to search for. Let's assume that the user chooses to search for wines made from the grape variety “lagrein.”
  2. You retrieve the user's search term, and save it by assigning it to a variable, something like this:
    $variety = $_POST['variety'];

    So that the value of the variable $variety is now this:

    lagrein
  3. You construct a database query, using that variable in the WHERE clause, something like this:
    $query = "SELECT * FROM wines ...

Get Pro PHP Security: From Application Security Principles to the Implementation of XSS Defenses, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.