Home > OS >  Is SQL injection possible with int data type?
Is SQL injection possible with int data type?

Time:08-29

Currently I'm not using prepare or bind statement in my php code but I'm taking only int data for my search query so I just want to know where SQL injection is even possible with this query?

$enroll = mysqli_real_escape_string($conn, intval($_POST['enroll']));

$result = mysqli_query($conn, "SELECT * FROM Student_Data WHERE enroll=$enroll LIMIT 1");

I use intval() to take Int only input.

Thank you for the information.

CodePudding user response:

In general, No It is not possible. But if your intension is to protect from SQL injection, why you should not use the better way which is proven? Overall, nothing can be guaranteed tomorrow. So better choice is to use the best practice what is available today.

CodePudding user response:

Firstly, escaping is always context-dependent. The context mysqli_real_escape_string is designed for is inside a single-quoted string in an SQL query. If you are using the string in any other context, do not use that function. For instance, this is not secure:

$input = "a   '   b";
$sql = "Select * From whatever Where something=" . mysqli_real_escape_string($conn, $input);

The result is this:

Select * From whatever Where something=a   ''   b

So you've gone from a syntax error to a valid, and user-controlled, query.

For that reason, applying both intval and mysqli_real_escape_string never makes sense: if you're using the value in an integer context, it's simply the wrong function, and a symptom of the dangerous mentality that "more escaping is better".


Secondly, understand what the functions you're using actually do: intval converts any PHP value, if it can, to an integer; then the . operator will always convert its operands to strings. So $anything . intval($input) is always converting $input first to an integer, and then to a string.

So, certainly we can predict exactly what characters are possible to end up in the query - digits 0 to 9, and the - sign. It's just about possible that some obscure bug in the database or driver could misinterpret those in such a way as to have unintended consequences, but it's pretty unlikely.


Thirdly, if you have the choice, just use parameters and the whole thing becomes irrelevant.

Remember that, since you no longer have the context it works with, you should not also use mysqli_real_escape_string.

  • Related