SyntaxStudy
Sign Up
MySQL Preventing SQL Injection
MySQL Intermediate 7 min read

Preventing SQL Injection

SQL injection is one of the most dangerous vulnerabilities in web applications. It occurs when user-supplied input is concatenated directly into a SQL query, allowing attackers to manipulate the query logic to bypass authentication, extract data, or destroy data.

How SQL Injection Works

If a login query is built like: "SELECT * FROM users WHERE username = '" + input + "'", an attacker can supply input like: ' OR '1'='1 to make the query always return true.

Prevention: Prepared Statements

The most effective prevention is using prepared statements (parameterized queries). The query structure is sent to the database separately from the data values. The database driver handles escaping, making injection structurally impossible.

  • Use prepared statements in all languages (PDO in PHP, PreparedStatement in Java, etc.)
  • Never concatenate user input into SQL strings
  • Validate and sanitize input as a defense-in-depth measure
  • Use stored procedures (they accept parameters, not raw SQL)
Example
-- VULNERABLE (never do this):
-- SELECT * FROM users WHERE username = "input";

-- SAFE: Use prepared statements
PREPARE stmt FROM "SELECT * FROM users WHERE username = ?";
SET @username = "alice";
EXECUTE stmt USING @username;
DEALLOCATE PREPARE stmt;

-- PHP PDO equivalent:
-- $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
-- $stmt->execute([$input]);
Pro Tip

Prepared statements make SQL injection structurally impossible — always use them for user-supplied input.