How to escape apostrophe (') in MySql?

前端 未结 10 633
孤城傲影
孤城傲影 2020-11-22 07:49

The MySQL documentation says that it should be \\\'. However, both scite and mysql shows that \'\' works. I saw that and it works. What should I d

相关标签:
10条回答
  • 2020-11-22 08:19

    Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to a SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too, but a simple option in PHP is to use the htmlspecialchars() function which will convert all your apostrophes into ' which is possibly what you want to store anyway.

    0 讨论(0)
  • 2020-11-22 08:20

    In PHP I like using mysqli_real_escape_string() which escapes special characters in a string for use in an SQL statement.

    see https://www.php.net/manual/en/mysqli.real-escape-string.php

    0 讨论(0)
  • 2020-11-22 08:27

    Replace the string

    value = value.replace(/'/g, "\\'");
    

    where value is your string which is going to store in your Database.

    Further,

    NPM package for this, you can have look into it

    https://www.npmjs.com/package/mysql-apostrophe

    0 讨论(0)
  • 2020-11-22 08:31

    There are three ways I am aware of. The first not being the prettiest and the second being the common way in most programming languages:

    1. Use another single quote: 'I mustn''t sin!'
    2. Use the escape character \ before the single quote': 'I mustn\'t sin!'
    3. Use double quotes to enclose string instead of single quotes: "I mustn't sin!"
    0 讨论(0)
提交回复
热议问题