StepCoding

Encoding SQL

อ่าน [919] หมวดหมู่: Encoding และ Escaping

ระบบฐานข้อมูล (database) ส่วนมากต้องการข้อความ (string) ในคำสั่ง SQL ของเราในรูปแบบที่ถูก escape แล้ว ในการ [storng]encode SQL ให้อยู่ในรูปแบบที่ถูกต้องก็คือการใส่ backslash (\) นำหน้าอักขระเหล่านี้เช่น single quotes, double quotes, NUM-bytes และ backslashes ซึ่งใน PHP ได้สร้างฟังก์ชันในการเพิ่ม backslash (\) เข้ามาหน้าอักขระเหล่านี้แล้ว นั่นก็คือฟังก์ชัน stripslashes() ดังนี้

<?php
$string = <<< The_End
"It's never going to work," she cried,
as she hit the backslash (\) key.
The_End.

echo addslashes($string);
?>
# ผลลัพธ์
\"It\'s never going to work, \" she cried,
as she hit the backslash (\\) key.

เมื่อเราทำการ escape อักขระต่าง ๆ เข้าสู่ฐานข้อมูลไปแล้ว เวลานำข้อมูลออกมาจาก ฐานข้อมูล เราก็จะต้อง decode กลับมา (นำ backslash (\) ออก) โดยใช้ฟังก์ชัน stripslashes()

<?php
$string = <<< The_End
\"It\'s never going to work, \" she cried,
as she hit the backslash (\\) key.
The_End;

echo stripslashes($string);
?>
# ผลลัพธ์
"It's never going to work," she cried,
as she hit the backslash (\) key.

ผู้สนับสนุน