The best way to prevent injection is to hack yourself (or at least think about it).
If you're expecting numerical input, don't could on a user to make it numerical.
Take a look at the following snippet:
PHP:
<?php
include 'mysql_connect.php';
if ($_GET['start'] && $_GET['end']) {
$start = mysql_real_escape_string($_GET['start']);
$end = mysql_real_escape_string($_GET['end']);
$query = mysql_query("Select name, rank from players where rank between $start and $end");
while ($row = mysql_fetch_array($query, MYSQL_NUM))
echo $row[0] . ": #".$row[1];
}
else
echo "Enter the Starting and ending ranks";
?>
This code is great right? I used mysql_real_escape_string and everything!
What happens if I enter '1' for start and '2 union Select name, password from players' for end?
I get the username and password for every entry in the table!
What did we do wrong here?
1. Obviously, we didn't use single quotes inside the mysql query. If you use single quotes surrounding every variable AND use mysql_real_escape_string, you're much safer.
2. We trusted user input. We didn't check if both $start and $end were numerical. We could have even been lazy and done $start = floor($start).
You'd be better off using is_int($start) at least is_numeric($start)
3. The code is lazy. It doesn't check if $Query actually worked, which can throw a mysql_fetch_array warning if there are no results. But this is because I was lazy writing my example, not trying to make a point.
So the whole point of this was to show you there isn't one fool-proof way to stop mysql injection. mysql_real_escape_string does not work every time.
You need to use your brain and understand how injection really works before you can defend against it.
Bruce