I have database tables in MySQL that have a primary keys defined as follows:
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
...
PRIMARY KEY (`id`)
I have already created models for the tables. I’m using Zend Framework v1, without an ORM, but this question should apply for all model implementations.
Now I want to create a function that allows me to grab by id:
public static function getById ($id) {
$id = intval($id);
if ($id < 1) {
throw new Exception('bad id');
}
// business logic and stuff
return $stuff;
}
The reason for this approach was twofold. Firstly, form input, including numbers, is often read from the view as a string. Secondly, invalid strings (such as 'asdf') would become zero after casting, thereby causing the exception to fire. However, there are many invalid strings that may still bypass the check:
echo intval('1asdf');
Output:
1
Other approaches I have tried include:
if (intval($id) === 0)
if ($id == intval($id))
What is the best way to validate the id in the model? I want it to accept integers greater than 0, and strings that are valid positive integers.
I would prefer something with a very low time cost. This is the reason I am not using regex to validate. These calls will be used everywhere in the application, and I cannot afford the overhead.
I cannot understand why you are going through so much trouble just to validate your input. Simply use the php functions is_numeric() and htmlentities() to check your input before passing it to your SQL logic. Moreover an Invalid Numeric ID (which isnt present in your database) will return null output when SQL against it is executed and that should’nt be an issue.
References:
is_numeric()
htmlentites()