开发者

Why do I get an SQL error when there is an apostrophe at the end of my URL?

Why do I get an error when I add ' to the end of a URL? For example : http://mywebsite.com/singel?id=24'

I g开发者_开发百科et the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\' LIMIT 1' at line 1

This is shown everywhere if I put ' after any id in the query string.

What is wrong, and how it can be fixed? Thank you.


You are inserting a non-escaped variable in an SQL query. And if this variable happens to contain SQL special chars, this can cause SQL syntax errors or worse.

You need to escape your variables before inserting them in your SQL queries.

Example:

$query = "SELECT * FROM users WHERE id = " . mysql_real_escape_string($id);

Instead of (this is WRONG, don't do this):

$query = "SELECT * FROM users WHERE id = $id LIMIT 1";

If $id is 24', the query becomes:

$query = "SELECT * FROM users WHERE id = 24' LIMIT 1";

As you can see, there is a ' after 24, which is a syntax error.


if a ' kills your query, you very obviously have an sql injection vulnerability. Read up on mysql_real_escape_string(), bobby-tables, and consider switching to PDO prepared statements.


Look here

http://www.codeproject.com/KB/database/SqlInjectionAttacks.aspx

You should learn something about SQL injection. Your Script is injectable now


This error usually means you are open to sql injections. This function is a bit more complicated than mysql_real_escape_string(), because it also does a PHP configuration test, to make sure you do not escape the data twice and to add Various PHP version support! (as per PHP Manual 1) Just run this little nifty function on each of the submitted items, for inserts, updates or where statements:

function sql_injection($value){
    $value = trim($value);
    if(get_magic_quotes_gpc())
        $value = stripslashes($value);
    if(function_exists("mysql_real_escape_string")){
        $value = mysql_real_escape_string($value);
    }else
        $value = addslashes($value);
    return $value;
}

Ex:

$q = 'SELECT `blah` FROM `users` WHERE `id`='.sql_injection($_POST['id']);
  • This function does NOT replace server side validation, and everything should be validated before using it, always assume the worst :)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜