Two things here. First, users make honest mistakes. Someone mistypes a product name, a price, or whatevs. You can have your program catch errors, before they pollute the app's database. Well, catch some errors, anyway.
There's a second reason to not trust user data: hacking. Entering strange data is one way people break into systems.
Suppose we're grabbing an id from GET, and using it to lookup a DB record. For example:
- $id = $_GET['id'];
We could insert
$id directly into a string, to make a query:
- $sql = "SELECT * FROM wombats WHERE wombat_id = $id;";
Easy enough, but that might leave the door open for hackers. Suppose a hacker typed:
- ...?id=3;DELETE * FROM wombat;
The SQL we'd run:
- SELECT * FROM wombats WHERE wombat_id = 3;DELETE * FROM wombat;
Wombat data gone! Not so good.
That's an SQL injection attack. It's the subject of a famous XKCD cartoon.
We use PHP's PDO library in this course. PDO sanitizes for you.