Thursday, 18 December 2014

How can I prevent SQL-injection in PHP [SOLVED]

How can I prevent SQL-injection in PHP [SOLVED]

Following are different 3 ways to prevent from SQL Injection.
1. Using PHP inbuilt Functions.
$name = mysql_real_escape_string($_POST["name"]);
mysql_query("INSERT INTO users VALUES($name)");


2. Use MySqli instead of MySQL. MySqli is far better than MySql because is object oriented MySql.
$stmt = $dbConnection->prepare('INSERT INTO users VALUES(?)');
$name=$_POST["name"];
$stmt->bind_param('s', $name);
$stmt->execute();


3. Using PDO
$stmt = $conn->prepare("INSERT INTO users VALUES(:name)");
$stmt->bindValue(':name', $_POST["name"]);
$stmt->execute();



2 comments:

Anonymous said...

when we have to use PDO & mysqli .. Please given relvant answer as per development application point of view

Arun Kumar said...

I would prefer PDO,

Both libraries are basically different flavors of the same thing (mysql connection).
1. With PDO, you can scale your application to use other databases with just a few code changes.
2. PDO library has much of the security built in
3. PDO Supports named parameters

Know More

Post a Comment