#19: SQL Injection Attacks

Because the queries that PHP passes to MySQL databases are written in the powerful SQL programming language, you run the risk of someone attempting an SQL injection attack by using MySQL in web query parameters. By inserting malicious SQL code fragments into form parameters, an attacker attempts to break into (or disable) your server.

Let's say that you have a form parameter that you eventually place into a variable named $product, and you create some SQL like this:

$sql = "select * from pinfo where product = '$product'";

If that parameter came straight from the form, use database-specific escapes with PHP's native functions, like this:

$sql = 'Select * from pinfo where product = '"' mysql_real_escape_string($product) . ...

Get Wicked Cool PHP 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.