problem with get url using php and mysql
Sorry if this question may seem easy to some but i cannot seem to figure it out. i was told that i could come here because the guys here are very helpful. i am having problem with the following code. when the uid is call into the url for example page.php?uid=5
i get "some code" if i do page.php?uid=letters
i get redirected to page.php?uid=1
. that works fine. but if a user should enter page.php?uid=1letters
i get this error..Unknown column '1gh' in 'where clause'
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\page.php on line 173.
i only get this error if the user enters unwanted characters at the end of get url id. How can i prevent this from happen how can i have it redirect to page.php?uid=1
... see code below
$id = mysql_real_escape_string(@$_GET['uid']);
$query = mysql_query("SELECT user.* FROM user WHERE id = '$id'");
if ((mysql_num_rows($query)==0)) {
header("location:page.php?uid=1");
die();
}
else {
while($rows = mysql_fetch_array($query)){
开发者_StackOverflow $foo = $row['foo'];
echo "some code";
mysql_query returns false on error. You should check what it returns:
$query = "SELECT user.* FROM user WHERE id = '$id'"
$result = mysql_query($query);
if ($result === false) {
die($query.'<br/>'.mysql_error());
}
Then you can understand why it failed. I've added the query to the die()
statement so you can try the query manually as well.
The error given is unknown column of a string, which suggests you are not enclosing the value with single quotes in the SQL query, even though the code in the question does.
In production you should be taking all steps you can to ensure errors are handled gracefully. In this case you will probably want the same behaviour as not finding a user:
header("location:page.php?uid=1");
精彩评论