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

廉价感情. 提交于 2019-12-01 23:42:45

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