paulus
paulus

Reputation: 655

usage of intval & real_escape_string when sanitizing integers

dear All.

I'm using integer PKs in some tables of mysql database. Before input from PHP script, I am doing some sanitizing, which includes intval($id) and $mysqli->real_escape_string().

The queries are quite simple

insert into `tblproducts`(`supplier_id`,`description`) values('$supplier_id','$description')

In this example, $description goes through real_escape_string(), while $supplier_id only being intval()'ed.

I'm just curious, if there're any situations, when I need to apply both intval and real_escape_string to integer I'm inserting into DB? So basically do I really need to use?

$supplier_id = intval($mysqli->real_escape_string($supplier_id));

Thank you.

Upvotes: 5

Views: 2325

Answers (3)

Marc B
Marc B

Reputation: 360762

Consider something like this:

$x = "50 O'Brien Family Members at a Bar";

Using intval() will give you an "escaped" value of

50

whereas real_escape_string will give you

50 O\'Brien Family Members at a Bar

real_escape_STRING() should only be used where you really do want to use a string value in a query. For everything else, use a more appropriate tool.

Upvotes: 1

James Williams
James Williams

Reputation: 4216

You do not have to use $mysqli->real_escape_string after running intval on an variable. intval() will return 0 if it is not an integer and if it is a integer it will return the value.

Example:
$variable = '5';
$variable2 = 'c5b';
if(intval($variable)) echo 'It is a variable'; # intval will return 5 or true
if(intval($variable2)) echo 'It is a variable'; # intval will return 0 or false since it has a letter

There is some cases where intval will return the first integer in the string if it is set to '5b'

Upvotes: 2

Derek
Derek

Reputation: 1055

intval way faster than real_escape_string since real_escape_string has to connect to the database and escaping based on the charset/collation.

you can also cast the int like:

$val = (int)$val;

therefore no need to double sanitize

Upvotes: 10

Related Questions