My approach to avoid sql injection::Html form
<form method="post" action="" style="padding:0;">
<p> <span class="cclogin-addon"><i class="fa fa-user fa-2x fa-spin"></i></span>
<input type="text" name="firstname" value="" placeholder="First Name">
</p>
<p>
<p> <span class="cclogin-addon"><i class="fa fa-envelope fa-2x fa-spin"></i></span>
<input type="text" name="Email" value="" placeholder="Your Email">
</p>
<p>
<input type="submit" name="Login" value="Submit">
</p>
</form>
Using ajax I am submitting my form and I also implemented captcha to my form. On the action file, followed is the code which save data to database as :
if(isset($_POST['Login'])&& ( $_POST['Login'] )) // submit button name
{
if($_POST['type_code']==$_SESSION['vercode']) // checking captcha code
{
$firstname = strip_tags($_POST['firstname']);
$email = strip_tags($_POST['email']);
$phone = $_POST['phone'];
$sql = "INSERT INTO table_name (firstname,email,phone)
VALUES ('".$firstname."', '".$email."','".$phone.")";
if ($conn->query($sql) === TRUE) {
echo ‘records save successfully’;
}
Else
{
Echo ‘not saved data’;
}
But after cross-site scripting scan I got lots of sql injection bugs For example :: URL encoded POST input firstname was set to ttqevjod" onmouseover=prompt(949671)
The input is reflected inside a tag parameter between double quotes. To avoid such bugs my second approach was to restrict user from entering escape sequence characters into text field
This is as follow:: 1. Check on key press event
function blockSpecialChar(id)
{
var spclChars = "!@#$%^&*,\'\"(;:?.|-_)<>&[]{}+=`\/";
var content = $('#'+id).val();
for (var i = 0; i < content.length; i++)
{
if (spclChars.indexOf(content.charAt(i)) != -1)
{
alert ("Special characters are not allowed.");
$('#'+id).val('');
return false;
}
}
}
While saving data
if(isset($_POST['Login'])&& ( $_POST['Login'] )) // submit button name
{
if($_POST['type_code']==$_SESSION['vercode']) // checking captcha code
{
$firstname = htmlspecialchars ($_POST['firstname']);
$email = htmlspecialchars ($_POST['email']);
$phone = htmlspecialchars($_POST['phone']);
$sql = "INSERT INTO table_name (firstname,email,phone)
VALUES ('".$firstname."', '".$email."','".$phone.")";
if ($conn->query($sql) === TRUE) {
echo ‘records save successfully’;
}
Else
{
Echo ‘not saved data’;
}
But my supervisor said this is wrong method of preventing sql injection. Please guide me right way of preventing sql injection.