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
Release: 2024-12-02 18:22:16
Original
931 people have browsed it

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.
Copy after login

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.';
Copy after login

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.';
Copy after login

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.');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template