$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','noreply@example.com');
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;
}