
Problem Description:
If user input data is inserted into an SQL query without proper handling, the application is likely vulnerable to SQL injection attacks, as shown in the following example:
- $unsafe_variable = $_POST['user_input'];
- mysql_query("INSERT INTO `table` (`column`) VALUES ('" . $unsafe_variable . "')");
:
- value'); DROP TABLE table;—
SQL:
- INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;–')
SQL?
(Theo):
。,。SQL。 :
1、PDO:
- $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
- $stmt->execute(array('name' => $name));
- foreach ($stmt as $row) {
- // do something with $row
- }
2、mysqli:
- $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
- $stmt->bind_param('s', $name);
- $stmt->execute();
- $result = $stmt->get_result();
- while ($row = $result->fetch_assoc()) {
- // do something with $row
- }
PDO
,PDOMySQL()。,PDO。PDO:
- $dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
- $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
- $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
,(ATTR_ERRMODE),。,(Fatal Error),,PDOExceptions,。 ,setAttribute(),PDO,,MySQL。MySQLPHP,SQL。,:PDOPDO。 PHP(<5.3.6),PDODSNSettings,:silently ignored the charset parameter。
SQL?(? :name),。execute,。 :SQL,SQL。SQLSQL。,SQL,SQL。,。,$name ’Sarah’; DELETE FROM employees , employees name ’Sarah’; DELETE FROM employees 。 :,,。 ,(PDO):
- $preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
- $preparedStatement->execute(array('column' => $unsafeValue));
: StackOverflow : – rokety
: http://blog.jobbole.com/67875/