I use query string to access my pages. I try to make if anyone type unknown query string manually, then redirect to somewhere..
For example:
Url: test.php?m=1 (this is a valid url)
test.php?m=1324234 (this is not a valid url )
test.php?m=1asdaa (this is not a valid url )
include("config/database.inc");
$qm=$_GET['m'];
$query = "select acc from test where acc=$qm";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
if ($numrows == 0){
header("Location: index.php");
exit;
}
In the database i have two line, LINE 1: acc=1; LINE 2: acc=2;
If i type to the url: test.php?m=12312431, then redirect to index.php ‘coz $numrows=0. Thats ok.
But if i type: test.php?m=1sdfsfsf, then i got this error msg.:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in..
How can i do that? Need to check the $_GET[‘m’] before query from database?
Thank you.
You should never be placing the value of a GET variable directly into an SQL query without properly filtering and escaping it. Your problem is that you’re allowing things which aren’t numbers to be put into your SQL query. In this particular case, your test is harmless and just errors, but a malicious user could also do things much more harmful via SQL injection.
Instead, what you really want to do is convert the variable’s value to a type that you know is okay (in this case, an integer) and then query the database using that. Try this instead:
Notice the call to intval() which forces the result to be an integer value, instead of potentially harmful strings.