Search code examples
phpmysqlisql-injection

How to use mysqli_real_escape_string for int value?


I have this $search= mysqli_real_escape_string($conn,$_POST['search']); Now, I want to know if this can be converted into int and would that be a safe option to avoid sql injection.

$sql ="SELECT * FROM basket WHERE quantity =$search";

**here quantity is int


Solution

  • Yes, strictly speaking, casting a variable with (int) or intval() removes the risk of that variable causing an SQL injection.

    But this is not a good reason to avoid using query parameters.

    For one thing, you might have both string and integer variables to combine with your SQL statement. It makes your code more complex to use different methods of making variables safe, depending on their type. If you just use query parameters for all variables, you simplify your code.

    Please just do it right.