Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธี Escape Apostrophe (Single Quote) ใน MySQL

มี 2 วิธีหลักในการ Escape Apostrophe (') ใน MySQL String Literal

วิธีที่ 1: Backslash (\) - Standard SQL Escape

INSERT INTO SingleQuotesDemo VALUES (1, 'John\'s');
-- หรือใน SELECT
SELECT 'John\'s';  -- ผลลัพธ์: John's

วิธีที่ 2: Double Single Quote ('') - ANSI SQL Standard

INSERT INTO SingleQuotesDemo VALUES (2, 'John''s');
-- หรือใน SELECT
SELECT 'John''s';  -- ผลลัพธ์: John's

ตัวอย่างเต็ม

CREATE TABLE SingleQuotesDemo (
    id INT,
    name VARCHAR(100)
);

-- ทดสอบ Backslash
INSERT INTO SingleQuotesDemo VALUES (1, 'John\'s');

-- ทดสอบ Double Quote
INSERT INTO SingleQuotesDemo VALUES (2, 'John''s');

SELECT * FROM SingleQuotesDemo;
+------+--------+
| id   | name   |
+------+--------+
| 1    | John's |
| 2    | John's |
+------+--------+

การ Escape อื่นๆ ใน MySQL String

Escape Sequenceความหมาย
\'Single Quote
\"Double Quote
\\Backslash
\nNewline (LF)
\rCarriage Return (CR)
\tTab
\bBackspace
\ZCtrl+Z (Windows EOF)
\%Percent (ใน LIKE)
\_Underscore (ใน LIKE)

⚠️ Best Practice: อย่า Escape เอง ใช้ Prepared Statements

-- ❌ ไม่ดี: Manual Escape (Risk SQL Injection)
$query = "INSERT INTO users (name) VALUES ('" . mysqli_real_escape_string($conn, $name) . "')";

-- ✅ ดี: Prepared Statement (Parameterized Query)
$stmt = $mysqli->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->bind_param("s", $name);
$stmt->execute();

สรุป

  • ใน SQL โดยตรง: ใช้ \' หรือ '' (ทั้งคู่ได้)
  • ใน Application: ห้าม Escape เอง ใช้ Prepared Statements เสมอ
  • MySQL รองรับ ANSI_QUOTES Mode: ถ้าเปิด " จะกลายเป็น Identifier, ' เท่านั้นสำหรับ String