Prevent code and data mixing. Prefer vetted persistence libraries or frameworks that provide safe database constructs, such as Hibernate or Enterprise Java Beans when used correctly. Process SQL with prepared statements, parameterized queries, or strongly typed stored procedures, and do not dynamically build and execute query strings inside them using exec or similar functionality.
Constrain inputs and mappings. Treat all external input as malicious and apply strict allowlists covering the expected type, length, syntax, range, related-field consistency, and business rules. Input validation is defense in depth rather than a replacement for correct encoding, escaping, and quoting, especially for free-form text. Where acceptable objects are known, map fixed input values such as numeric IDs to those objects and reject other values. Duplicate client-side security checks on the server.
Protect unavoidable dynamic construction. If dynamic query construction cannot be avoided, properly quote arguments and escape special characters. Use the strictest practical allowlist, and use database or language facilities such as Oracle DBMS_ASSERT or the MySQL mysql_real_escape_string API where applicable. This approach remains risky and must also consider argument injection.
Reduce impact and information disclosure. Run database accounts with least privilege, preferably isolated accounts limited to one task, and grant only the minimum permissions on database objects. Do not run ordinary database applications as an administrator; restrict access to the caller's permitted data and use the strictest stored-procedure permissions possible. Keep error messages minimal and avoid exposing SQL query structure or inconsistent internal state; retain necessary detail in carefully protected logs and never log passwords. In PHP, do not use register_globals and do not emulate it in a way that introduces related weaknesses.
Add operational defense in depth. An application firewall can detect and block attacks when code cannot immediately be fixed, or provide emergency protection while stronger assurance measures are applied. Its coverage is limited, and it may be bypassed, interfere with legitimate requests, or require customization.