Before we go to discuss the techniques, We should known what is SQL injection?
SQL injection is one of the attack in which vulnerable code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution.
There are two ways to avoid the SQL injection.
- Use prepared statements or parameterized queries
- Use escape in input string
Use prepared statements or parameterized queries: It is one of the way to process the input data by SQL server seprately . This way it is impossible for an attacker to inject malicious SQL.
By Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE emp_id= :emp_id');
$stmt->execute(array('emp_id' => $id));
By Using Mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE emp_id = ?');
Use escape in input string : It is another way to avoid SQL injection. Whenever you use dynamic values in your query then you must escape it before use it in your query.
When you inject some expected integer value into an SQL query, make sure it’s an integer,by using
When you have a decimal/numeric field in your table, use
And when you have a string (char, varchar, text) field in your table, use the function provided by your API to escape strings :
Please don’t forget to share and subscribe to latest updates of the blog.