Pages

Monday, June 22, 2015

How can i prevent SQL - injection in PHP ?

Your Basically Have 2 options to achieve this Answer 



$st = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

      $st->execute(array('name' => $name));

       foreach ($st as $row) {
                                                       // do something with $row
}

Using MYSQLi ( for  MYSQL )     :

$st = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$st->bind_param('s', $name);

$st->execute();

$result = $st->get_result();
while ($row = $result->fetch_assoc()) {
                                                       // do something with $row
}
Using MYSQLi ( for  MYSQL )     :
 
→  if you are connecting Database or MYSQL then refer to (e.g. pg_prepare() and pg_execute() for PostgreSQL).

correct setting for this connection.

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'username', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 in above example the ERRMODE is not compulsary but necessary is when you are set setattribute() line 

Note → it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.


Related Language    :      PHP     MYSQL     SQL     Security     SQL-injection