Sobes.tech
Junior — Middle

What techniques and methods exist to protect a database from SQL injections?

sobes.tech AI

Answer from AI

Main methods of protecting a database from SQL injections:

  • Using prepared statements and parameterized queries. This is the most effective way, as parameters are not interpreted as part of SQL.
  • Escaping special characters in user input (for example, using functions like mysqli_real_escape_string in PHP).
  • Using ORM (Object-Relational Mapping), which automatically generates safe queries.
  • Limiting database access rights to minimize damage in case of an attack.
  • Validating and filtering user input at the application level.

Example of using prepared statements in PHP with PDO:

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $userInputEmail]);
$results = $stmt->fetchAll();

This approach prevents malicious SQL code injection.