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

前端 未结 10 1077
不知归路
不知归路 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条回答
  •  萌比男神i
    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.

提交回复
热议问题