[mysql] How to escape single quotes in MySQL

How do I insert a value in MySQL that consist of single or double quotes. i.e

This is Ashok's Pen.

The single quote will create problems. There might be other escape characters.

How do you insert the data properly?

This question is related to mysql string quotes

The answer is


You should escape the special characters using the \ character.

This is Ashok's Pen.

Becomes:

This is Ashok\'s Pen.

The way I do, by using Delphi:

TheString to "escape":

TheString=" bla bla bla 'em some more apo:S 'em and so on ";

Solution:

StringReplace(TheString, #39,'\'+#39, [rfReplaceAll, rfIgnoreCase]);

Result:

TheString=" bla bla bla \'em some more apo:S \'em and so on ";

This function will replace all Char(39) with "\'" allowing you to insert or update text fields in MySQL without any problem.

Similar functions are found in all programming languages!


Maybe you could take a look at function QUOTE in the MySQL manual.


In PHP, use mysqli_real_escape_string.

Example from the PHP Manual:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

For programmatic access, you can use placeholders to automatically escape unsafe characters for you.

In Perl DBI, for example, you can use:

my $string = "This is Ashok's pen";
$dbh->do("insert into my_table(my_string) values(?)",undef,($string)); 

Use either addslahes() or mysql_real_escape_string().


If you are using PHP, just use the addslashes() function.

PHP Manual addslashes


You can use this code,

<?php
     $var = "This is Ashok's Pen.";
     addslashes($var);
?>

if mysqli_real_escape_string() does not work.


See my answer to "How to escape characters in MySQL"

Whatever library you are using to talk to MySQL will have an escaping function built in, e.g. in PHP you could use mysqli_real_escape_string or PDO::quote


' is the escape character. So your string should be:

This is Ashok''s Pen

If you are using some front-end code, you need to do a string replace before sending the data to the stored procedure.

For example, in C# you can do

value = value.Replace("'", "''");

and then pass value to the stored procedure.


If you use prepared statements, the driver will handle any escaping. For example (Java):

Connection conn = DriverManager.getConnection(driverUrl);
conn.setAutoCommit(false);
PreparedStatement prepped = conn.prepareStatement("INSERT INTO tbl(fileinfo) VALUES(?)");
String line = null;
while ((line = br.readLine()) != null) {
    prepped.setString(1, line);
    prepped.executeQuery();
}
conn.commit();
conn.close();

There is another way to do this which may or may not be safer, depending upon your perspective. It requires MySQL 5.6 or later because of the use of a specific string function: FROM_BASE64.

Let's say you have this message you'd like to insert:

"Ah," Nearly Headless Nick waved an elegant hand, "a matter of no importance. . . . It's not as though I really wanted to join. . . . Thought I'd apply, but apparently I 'don't fulfill requirements' -"

That quote has a bunch of single- and double-quotes and would be a real pain to insert into MySQL. If you are inserting that from a program, it's easy to escape the quotes, etc. But, if you have to put that into a SQL script, you'll have to edit the text (to escape the quotes) which could be error prone or sensitive to word-wrapping, etc.

Instead, you can Base64-encode the text, so you have a "clean" string:

SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K

Some notes about Base64-encoding:

  1. Base64-encoding is a binary encoding, so you'd better make sure that you get your character set correct when you do the encoding, because MySQL is going to decode the Base64-encoded string into bytes and then interpret those. Be sure base64 and MySQL agree on what the character encoding is (I recommend UTF-8).
  2. I've wrapped the string to 50 columns for readability on Stack Overflow. You can wrap it to any number of columns you want (or not wrap at all) and it will still work.

Now, to load this into MySQL:

INSERT INTO my_table (text) VALUES (FROM_BASE64(' SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K '));

This will insert without any complaints, and you didn't have to manually-escape any text inside the string.


$var = mysqli_real_escape_string($conn, $_POST['varfield']);

If you want to keep (') apostrophe in the database use this below code:

$new_value = str_replace("'","\'", $value); 

$new_value can store in database.


Use this code:

<?php
    $var = "This is Ashok's Pen.";

    mysql_real_escape_string($var);
?>

This will solve your problem, because the database can't detect the special characters of a string.


Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to quotes

YAML: Do I need quotes for strings in YAML? Regex to split a CSV Expansion of variables inside single quotes in a command in Bash How to call execl() in C with the proper arguments? Insert text with single quotes in PostgreSQL When to use single quotes, double quotes, and backticks in MySQL Difference between single and double quotes in Bash Remove quotes from a character vector in R How do I remove quotes from a string? How can I escape a double quote inside double quotes?