Is that OK to not sanitize before inserting into DB?

I have this to show pages of datas in table grid


$limit = 10;
$start = (isset($_GET['page']) AND $_GET['page'] > 0) ? $_GET['page'] * $limit : 0;

$sql = mysql_query("SELECT * FROM TABLE_1 WHERE col='$foo' ORDER BY id DESC LIMIT $start, $limit", $conn) or die();

while ($row = mysql_fetch_array($sql)) {.........}

I didn’t have treatment for user input of $_GET[‘page’], since the boolean condition $_GET[‘page’] > 0 accepts ONLY numeric number in order for it to be TRUE.

I hope I am not wrong…else i must then spend extra day or 2 to mod the code.

or is that necessary to add is_numeric()? into:–


$start = (isset($_GET['page']) AND is_numeric($_GET['page']) AND $_GET['page'] > 0) ? $_GET['page'] * $limit : 0;

PHP will automatically convert number-strings to numbers when used in comparison statements. Non-Number strings are treated as 0.

It’s always a good practice to sanitize any user input if it’s going to be used in a SQL query; while your script already does that (multiplying the string renders it’s value, which is 0 for non-number strings), this is a rare circumstance where the code takes care of the sanitization for you.

In a case like this (note, I’m an OO programmer) I would create a (set of) validation class(es) which automate the process. Then you only have to run each input through the appropriate validation class and you know it’s safe. Then you can work with it however you want. It really simplifies the validation process and at least makes it look easy to all of your code.

Inside the validation class, I would follow best practice, and use a whitelist to allow only appropriate input.