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.
The intval() function returns the integer value of a variable.
intval — Get the integer value of a variable.
The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.
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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With