How to prevent SQL-injection in PHP?
- Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters.
- This way it is impossible for an attacker to inject malicious SQL.
Php5 and later versions have introduced two options to help us preventing from SQL injection.
- Using MySQLi (for MySQL):
Example:
$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 }
- Using PDO (for any supported database driver):
Example:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array('name' => $name)); foreach ($stmt as $row) { // do something with $row }