To prevent SQL injection attacks treat all user input as potentially malicious and follow some programming guidelines:
Filter User Input
For an attacker to successfully execute an SQL injection, he needs to plant some code that is run by the web application's database. Therefore all user input should be validated first and limited to the needed characters. E.g. you may ask a user to input a username, password and e-mail address in a registration form. You can limit the allowed characters of these input fields to characters that do not interfere with the database. The following example filters out user input for the three values in PHP:
Most modern web frameworks provide some abstraction of the database handling. E.g. Laravel provides Eloquent queries. Created objects are automatically converted and stored or retrieved from the database. In the example of the user registration form, one could create the user object in the following way:
The resulting SQL statement is automatically sanitized and will prevent SQL injections.
Sanitize User Input / Prepared Statements
It may not always be possible to use a database mapper. In these cases use prepared statements to create your SQL queries. These form of statements validate and sanitize the user provided values and therefore prevent SQL injections. E.g. in PHP you can create a prepared statement the following way:
For more information visit https://crashtest-security.com