ฟังก์ชัน mysql_* ทั้งหมด Deprecated แล้ว (PHP 5.5+) และ Removed ใน PHP 7.0+ ควรใช้ mysqli หรือ PDO แทน
เปรียบเทียบ (สำหรับ Legacy Code เท่านั้น)
| Function | Return Type | Key Type | คำอธิบาย |
|---|---|---|---|
mysql_fetch_assoc() | Associative Array | Column Name (String) | คืนค่า ['col' => 'val'] ใช้ Key เป็นชื่อคอลัมน์ |
mysql_fetch_array() | Array (Both) | Numeric + String | คืนค่าทั้ง Numeric Index และ Associative (Default: MYSQL_BOTH) ใช้ Memory มากกว่า |
mysql_fetch_row() | Numeric Array | Numeric (0,1,2...) | คืนค่า ['val1', 'val2'] เร็วที่สุด, ใช้ Memory น้อยสุด |
mysql_fetch_object() | Object (stdClass) | Property Name | คืนค่า Object $row->col ไม่ใช่ Array |
ตัวอย่างผลลัพธ์
-- mysql_fetch_assoc Array ( [id] => 1, [name] => 'John' ) -- mysql_fetch_array (MYSQL_BOTH) Array ( [0] => 1, [id] => 1, [1] => 'John', [name] => 'John' ) -- mysql_fetch_row Array ( [0] => 1, [1] => 'John' ) -- mysql_fetch_object stdClass Object ( [id] => 1, [name] => 'John' )
แนวทางปัจจุบัน (mysqli / PDO)
-- mysqli (Procedural) $row = mysqli_fetch_assoc($result); // แนะนำใช้ associative -- PDO $row = $stmt->fetch(PDO::FETCH_ASSOC); // default คือ FETCH_BOTH
สรุป: อย่าใช้ mysql_* ใหม่เลย ใช้ PDO (แนะนำ) หรือ mysqli ด้วย FETCH_ASSOC สำหรับ Code ใหม่ ทั้งคู่รองรับ Prepared Statements ป้องกัน SQL Injection