Search code examples
phpsqlpdosql-injection

Can this prepared statement prevent SQL injection?


$string = trim($_POST['string'])
$sql = "INSERT INTO table (string) VALUES(:string)";
$query = $db->prepare($sql);
$query->execute(array(
    ":string" => $string
));

Can this block of code prevent SQL injection?

EDIT:
This is the connection that I am making to the database. Does the charset of this code allows the above block of code to be executed and prevent the SQL injection?

//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','table');

//application address
define('DIR','http://localhost/');
define('SITEEMAIL','[email protected]');

try {

//create PDO connection 
$db = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

} catch(PDOException $e) {
//show error
echo 'Looks like server is down please check back later';
exit;
}

Solution

  • Yes it will prevent SQL injection because

    Prepared statements uses bound parameters.

    Prepared Statements do not combine variables with SQL strings, so it is not possible for an attacker to modify the SQL statement.

    Prepared Statements combine the variable with the compiled SQL statement, this means that the SQL and the variables are sent separately and the variables are just interpreted as strings, not part of the SQL statement.