SQL
injection?In simple terms, SQL
injection is simply a person trying to maneuver your SQL
queries by sending in SQL
commands through input fields provided to them at the users' end. In PHP, this can be done by sending these commands through the user registration form or comment form. In this shot, we will see how to prevent SQL
injection in PHP.
SQL
in PHPTo ensure we have a secured website that is not vulnerable to SQL
injection, we have to make sure the connection to our database is very secured.
SQL
database?We will use the php pdo
to create our connection like so:
<?php$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'root', '');$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
php pdo
.Note: Here, we're assuming that you know how to setup connection to your
SQL
database usingpdo
, and the script above is just to improve security.
SQL
injection prevention, inside the setAttribute()
method, which tells PDO
to use actual prepared statements while disabling emulated prepared statements. This gives no opportunity to an attacker to inject malicious SQL
commands.