What is SQL injection and how to prevent it in PHP?
SQL injection is an attack where a visitor types SQL code in a form or URL, and your script runs it as part of the query. The attacker can read, change or delete data of your database.
It happens when you put user input directly inside the SQL text.
<?php
// Unsafe: the email comes from the form and goes directly in SQL
$email = $_POST["email"];
$sql = "SELECT * FROM users WHERE email = '$email'";
?>
If the visitor types ' OR '1'='1, the condition is always true and the query returns every user.
How to prevent it: use prepared statements. The SQL and the data are sent separately, so the data can never become a part of the SQL.
<?php
$stmt = $conn->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
?>
- Use prepared statements with mysqli or PDO for every query that has user data.
- Never build SQL by joining strings with variables.
- Give the database user only the permissions it needs.
- Do not show database errors to visitors.
Full examples are in PHP MySQL Prepared Statements.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |