Home >Database >Mysql Tutorial >How Can I Escape Single Quotes When Inserting Data into MySQL?

How Can I Escape Single Quotes When Inserting Data into MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 18:22:16934browse

How Can I Escape Single Quotes When Inserting Data into MySQL?

Escaping Single Quotes in MySQL

Inserting values containing single or double quotes into MySQL can be tricky due to syntax issues. Let's explore how to escape these characters for proper data insertion.

Problem:

Consider the following string:

This is Ashok's Pen.

When inserting this value into a MySQL database, the single quote in "Ashok's" can cause errors.

Solution:

There are two common methods for escaping single quotes:

Method 1: Double Quotes

Enclose the single quote within two double quotes. For example:

SELECT 'This is Ashok''s Pen.';

This method essentially replaces each single quote inside the string with two single quotes.

Method 2: Escape Character

Use the backslash () as an escape character before the single quote. For example:

SELECT 'This is Ashok\'s Pen.';

This method instructs MySQL to treat the following character as a literal rather than a special character.

Example:

Let's insert the sample value into a table:

INSERT INTO table_name (name) VALUES ('This is Ashok''s Pen.');

Using any of the above methods will ensure that the single quote is inserted into the database as a character rather than an SQL delimiter.

The above is the detailed content of How Can I Escape Single Quotes When Inserting Data into MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn