MySQL error when inserting data containing apostrophes (single quotes)?

前端 未结 10 1016
不知归路
不知归路 2020-11-30 13:59

When I an insert query contains a quote (e.g. Kellog\'s), it fails to insert a record.

ERROR MSG:

You have an error in your SQL s

相关标签:
10条回答
  • 2020-11-30 14:10

    Replace mysql with mysqli. Use this

    mysqli_real_escape_string($connection,$_POST['Description'])
    
    0 讨论(0)
  • 2020-11-30 14:16

    You can also use the addslashes() function which automatically puts \ before ' to avoid error

    0 讨论(0)
  • 2020-11-30 14:18

    In standard SQL, you use two single quotes to indicate one single quote, hence:

    INSERT INTO SingleColumn(SingleChar) VALUES('''');
    

    The first quote opens the string; the second and third are a single quote; and the fourth terminates the string. In MySQL, you may also be able to use a backslash instead:

    INSERT INTO SingleColumn(SingleChar) VALUES('\'');
    

    So, in your example, one or both of these should work:

    INSERT INTO UnidentifiedTable
        VALUES('Kellog''s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--');
    INSERT INTO UnidentifiedTable
        VALUES('Kellog\'s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--');
    

    In PHP, there is a function to sanitize user data (mysql_real_escape_string) before you embed it into an SQL statement -- or you should use placeholders. Note that if you do not sanitize your data, you expose yourself to SQL Injection attacks.

    0 讨论(0)
  • 2020-11-30 14:23

    Escape it by using a helper function like:

    function safeDBname($table_name)
    {
      $outputText=str_replace("'","",$outputText);
      return strtolower($outputText);
    }
    
    0 讨论(0)
  • 2020-11-30 14:25

    i did it as below-

    in my case description field contains apostrophe(').

    and here is code:

    $description=mysql_real_escape_string($description);
    
    "insert into posts set name='".$name."', address='".$address."', dat='".$dt."', description='".$description."'";
    

    it solved my problem

    0 讨论(0)
  • 2020-11-30 14:26

    You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string) using a \.

    Add a \ before the apostrophe in Kellogg's, giving you Kellogg\'s.

    0 讨论(0)
提交回复
热议问题