I use query string to access my pages. I try to make if anyone type unknown query string manually, then redirect to somewhere..
For ex开发者_如何学编程ample:
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:
include("config/database.inc");
$qm=intval($_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;
}
Notice the call to intval() which forces the result to be an integer value, instead of potentially harmful strings.
Do this:
$qm=intval($_GET['m']);
if m is invalid, mysql_query will return $query = false.
If you provide "false" to mysql_num_rows, it does not know what query you sent, and correctly get an invalid numrows result, e.g. a failure.
Check that m is integer with intval($m);
As well as validating the input or forcing a typecast as others have suggested to make sure the input makes sense, try to get into the habit of enclosing user-submitted values passed to a query in quotes, e.g.
$query = "select acc from test where acc='$qm'";
Although here you're technically comparing an integer to a string, MySQL allows this (and will still use integer keys where available), and it provides one last line of defence if you forget to filter the input.
精彩评论