The best way to avoid SQL injection for defined value type such as numbers, is to validate the value; since it is easier to do so comparing with mysqli preparation. In PHP, we can do this by.
1. if(!is_numeric($value)) {$value=0;}
2. $value=floatval($value);
3. $value=intval($value);
4. $value=$value * 1;
What is the most reliable one? or a better idea?
UPDATE: Although I have stated in the original question, most of folks emphasized the usefulness of parameterized queries. Definitely, it is the most efficient way to avoid SQL injection. But when we can simply validate an integer numeric value; IMHO, there is no need to parametrization.
For integers and floats you can use this if you don’t want to do a parameterised query.
These are actually casting the value as
intandfloat, this is faster thanintval()andfloatval()for example because it does not suffer the function overhead.