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

☆樱花仙子☆ 提交于 2019-12-02 03:40:58

问题


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?


回答1:


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.)




回答2:


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'])."')";



回答3:


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();
?>



回答4:


           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."')


来源:https://stackoverflow.com/questions/5125785/why-string-with-single-quotes-raises-error-when-inserted-in-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!