Hi, I recently came across a suggestion to insert (int) in a MySQL query before the id when the $sid is expected to be an integer but was wondering what the expected norm as far as security and reliability is concearned. I used to just check that an id variable actually had a value and that the value was numeric (although yes it should be an integer), so I guess my question is would this be considered better practice to use (int) as shown or is it considered better to check the id is an integer before it gets to this stage:
<?php
$qry = ("SELECT * FROM `service` WHERE `sid`=" . (int) $sid);
$rslt = @mysql_query($qry) or die (mysql_error());
?>
I guess the advantage with this is it the value is a string it would be then converted to an integer but I have not had any issues with an id being passed as a string 'that I know of anyway', MySQL seems to take over.
Your query that you are building in php simply gets passed as a string to mysql. mysql will do it's own interpreting from there. forcing a typecast on the value could conceivably result in wonky behavior:
I would say you're pretty safe doing the typecast unless you have '0' as an ID. The way php type converts a string to a number (very simply put) is by reading the string from left to right, and going until it finds a character other than a number. This results in "01C1" coming out to 1. 01 == 1.
It's excellent practice to validate your data types before shoving them at the database, to make a long story short.
I would always use type casting or mysql_real_escape_string at query time, in case the code is moved and you forget to check if its an int. If you put the typecast inline you dont have to worry abuot if it was escaped earlier
So if someone gets a string in an input you're throwing an exception? Most of the time PHP can recover gracefully (int)"52test" === 52; (int)"test" === 0 // better then throwing an exception IMO
jshpro2 wrote:So if someone gets a string in an input you're throwing an exception? Most of the time PHP can recover gracefully (int)"52test" === 52; (int)"test" === 0 // better then throwing an exception IMO
How do you differ a real zero value and a parsing error value (zero too)?
I don't like "gracefully processed" (lazy ) stuff - HTML vs. XHTML for example.
There are 10 types of people in this world, those who understand binary and those who don't