0

Am trying to deploy my application online. Every sql statements where written with PDO. I know how to do all sorts of validations and sanitization.

with the sample codes below. Am I protected against sql injection attack

connect.db

$db = new PDO ('mysql:host=localhost;dbname=mydbinfo;charset=utf8', 'root', 'ROOT123');

data.db

// select
$query = $db->prepare('SELECT * FROM users where username = :username');
$query->execute( array(':username' => $_POST['username']) );


//insert

$ins = $db->prepare('insert into users(username)values(:username)');
$ins->execute( array(':username' => $_POST['username']) );
jmarkatti
  • 621
  • 8
  • 29
  • 1
    The answer is YES – RiggsFolly Jun 06 '19 at 15:24
  • However using the `root` account for you app is a bad idea, specially with a simple password like that. Setup a new account that is only allowed to connect to the one database and from the one location(your web server). And give it only the privileges it actually requires on that database – RiggsFolly Jun 06 '19 at 15:25
  • okay root account I will change that. but about PDO protection which am troubled at. A friend of mine who is also told me that PDO works by mimicking the mysql_real_escape_string() and thus cannot escape single quote character ( ') character – jmarkatti Jun 06 '19 at 15:28
  • Then I suggest you place that friend in the _"Not quite as reliable/well informed as I thought (s)he was group"_ – RiggsFolly Jun 06 '19 at 15:29
  • Thanks Sir RiggsFolly for response so far. I ask one final question. can I also add this line of code $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); Is there any need for that – jmarkatti Jun 06 '19 at 15:32
  • 1
    Maybe you should read [this answer](https://stackoverflow.com/a/10455228/2310830) for info on ATTR_EMULATE_PREPARES – RiggsFolly Jun 06 '19 at 15:34
  • 1
    Thanks ** Sir Rigsfolly and TreyBake. ** From the two links you sent. I now learnt that PDO cannot fully protect from sql injection attack that its necessary to disable pdo emulations via this line of code $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); which tells PDO to disable emulated prepared statements and use real prepared statements. Accoding to the source from the links. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL). – jmarkatti Jun 06 '19 at 15:54

0 Answers0