PHP MYSQL

SQL INJECTION & PREVENTION IN PHP MYSQL

(a quick example)

ID           | Primary key. NAME    | Name. STATUS | 1 for active, 0 for hidden.

DUMMY DATABASE

01

SQL INJECTION (A)

02

CONNECT TO DATABASE $pdo = new PDO("mysql:host=HOST; charset=utf8dbname=NAME", USER, PASSWORD);

USER ENTERS SEARCH TERM $_POST["search"] = ‘" OR 1=1 OR `name` LIKE "’;

SQL INJECTION (B)

03

SEARCH DATABASE $stmt = $pdo->prepare("SELECT * FROM `TABLE` WHERE `status`=1 AND `name` LIKE \"%".$_POST["search"]."%\""); $stmt->execute(); $results = $stmt->fetchAll();

OUTPUT ALL BECAUSE SQL BECAME SELECT * FROM `TABLE` WHERE `status`=1 AND `name` LIKE "%" OR 1=1 OR `name` LIKE "%"

PREVENT INJECTION

04

CHANGE VALUES INTO ? $stmt = $pdo->prepare(  "SELECT * FROM `TABLE` WHERE `status`=1 AND `name` LIKE ?");

FEED DATA INTO EXECUTE() $stmt->execute   (["%".$_POST["search"]."%"]);

GET RESULTS $results = $stmt->fetchAll();