มี 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 |
| \n | Newline (LF) |
| \r | Carriage Return (CR) |
| \t | Tab |
| \b | Backspace |
| \Z | Ctrl+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