开发者

Why string with single quotes raises error when inserted in DB?

My question is: How do you allow single quotes in strings?

For example, I have a form, and a text box. 开发者_如何转开发It is set up to allow the user to enter their name. From there, it posts and feeds the data into a database.

I need to be able to allow single quotes (apostrophe) as some people's names have an apostrophe in their names, such as "O'Reilly".

Any suggestions?


Single quotes are not forbidden in any way. I'll simply assume that you got an error inserting it into the database. This is likely due to the omission of mysql_real_escape_string() on input values.

You will get an SQL error if you try INSERT ... ('O'Reilly') which is the whole point of the SQL escaping functions.

(This is why magic_quotes were originally introduced: to make SQL work out of the box for newcomers. - Not to make that particularly secure.)


Use the mysql_real_escape_string() function on any text that you insert into your database. You might be getting an error in your script if you are posting the data directly into your database because what you are actually doing is ending the MySQL quote.

It's also a security necessity that you escape your data. Something like the following is what you should have:

$q = "INSERT INTO `table` (`body`) VALUES ('".mysql_real_escape_string($_POST['body'])."')";


If I am reading your question correctly, you have coded an SQL Injection bug into your program, allowing slightly malicious people and viruses to read and write your database. (Imagine someone typing in ';drop table users; into a field... goodbye data.)

The easiest way to combat SQL Injection attacks is to write your SQL queries using prepared statements, which ask the database libraries to handle input data safely:

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>


           USe like:-

           insert into question(question,points,choice1,choice2,
           choice3,choice4,choice3_correct,tags,error_status,
           base_or_derived,language)    
           values('".mysql_real_escape_string($result4)."',
           '".$points."','".$ans1."','".$ans2."',
           '".$correct_ans."','".$ans3."','1','".$tags."',
            '".$error."','D','".$language."')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜