SQL injection occurs when an application treats untrusted input as part of a database command. An attacker may then read or change data that the application did not intend to expose.
Use parameterised queries
Keep the query structure separate from values supplied by users. Prepared statements bind those values as data rather than inserting them into the SQL text.
For example, with an existing MySQLi connection in $conn and a username in $username:
$stmt = $conn->prepare('SELECT id FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();The question mark is a value placeholder. Retrieve the result using your application’s normal result-handling code and close the statement when finished. Apply the same approach to updates, inserts and deletes that accept external input.
Placeholders cannot stand in for table names, column names or SQL keywords. If users can choose a sort order or similar option, map their choices to a fixed list of trusted SQL fragments.
Validate input and restrict access
Check input against the application’s expected type, length and format. Validation supports correct behaviour but does not replace parameterised queries.
Give the application’s database account only the permissions it needs. Avoid using an administrative database account for normal website requests.
Stored procedures and database libraries still need review: dynamic SQL inside a procedure or a raw query in a library can introduce the same vulnerability.
Handle passwords and errors safely
Do not authenticate users by comparing plaintext passwords in a SQL query. Store password hashes and verify passwords with the language’s supported password functions, such as PHP’s password_hash() and password_verify().
Show users a general error message while recording useful diagnostic details in protected logs. Keep database credentials, SQL statements and private data out of public error pages.
Review the application
Keep the application and its dependencies updated. Review every place that constructs SQL from external input and test the fixes in an authorised test environment. A web application firewall can provide an additional layer of protection, but it does not repair unsafe application code.