เราใช้ MySQL เวอร์ชัน 8.0.12 มาดูวิธีตรวจสอบเวอร์ชัน MySQL กันก่อน:
mysql> select version(); +-----------+ | version() | +-----------+ | 8.0.12 | +-----------+ 1 row in set (0.00 sec)
ชนิดข้อมูล Boolean ใน MySQL
ใน MySQL สามารถใช้ BOOL, BOOLEAN หรือ TINYINT(1) สำหรับค่า Boolean หากใช้ BOOL หรือ BOOLEAN MySQL จะแปลงเป็น TINYINT(1) ภายในระบบโดยอัตโนมัติ
สำหรับชนิดข้อมูล BOOL หรือ BOOLEAN ค่า true จะแสดงเป็น 1 และ false จะแสดงเป็น 0 เช่นเดียวกับภาษา PHP, C, C++
พิสูจน์ว่า MySQL แปลง BOOLEAN เป็น TINYINT(1)
ลองสร้างตารางที่มีคอลัมน์ BOOLEAN:
mysql> create table BoolOrBooleanOrTinyintDemo ( Id int NOT NULL AUTO_INCREMENT, isvalidAddress BOOLEAN, PRIMARY KEY(Id) ); Query OK, 0 rows affected (0.74 sec)
ตรวจสอบโครงสร้างตารางด้วยคำสั่ง SHOW CREATE TABLE:
mysql> show create table BoolOrBooleanOrTinyintDemo\G
ผลลัพธ์:
*************************** 1. row *************************** Table: BoolOrBooleanOrTinyintDemo Create Table: CREATE TABLE `boolorbooleanortinyintdemo` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `isvalidAddress` tinyint(1) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci 1 row in set (0.00 sec)
สังเกตคอลัมน์ isvalidAddress ชนิดข้อมูล BOOLEAN ถูกแปลงเป็น tinyint(1) ภายในระบบ ตอนนี้ลองตรวจสอบว่าค่า true แสดงเป็น 1 และ false แสดงเป็น 0 จริงหรือไม่ โดยการเพิ่มข้อมูล:
mysql> insert into BoolOrBooleanOrTinyintDemo(isvalidAddress) values(true); Query OK, 1 row affected (0.43 sec) mysql> insert into BoolOrBooleanOrTinyintDemo(isvalidAddress) values(false); Query OK, 1 row affected (0.17 sec) mysql> insert into BoolOrBooleanOrTinyintDemo(isvalidAddress) values(true); Query OK, 1 row affected (0.29 sec) mysql> insert into BoolOrBooleanOrTinyintDemo(isvalidAddress) values(false); Query OK, 1 row affected (0.12 sec) mysql> insert into BoolOrBooleanOrTinyintDemo(isvalidAddress) values(true); Query OK, 1 row affected (0.33 sec)
แสดงข้อมูลทั้งหมด:
mysql> select *from BoolOrBooleanOrTinyintDemo;
ผลลัพธ์:
+----+----------------+ | Id | isvalidAddress | +----+----------------+ | 1 | 1 | | 2 | 0 | | 3 | 1 | | 4 | 0 | | 5 | 1 | +----+----------------+ 5 rows in set (0.00 sec)
เห็นชัดว่าค่า true แสดงเป็น 1 และ false แสดงเป็น 0
การทำงานของ Boolean ใน PHP
ใน PHP ค่า true จะแสดงเป็น 1 และ false จะแสดงเป็น 0 เช่นกัน ดูตัวอย่างโค้ด PHP ต่อไปนี้:
$isValidAddress = 1;
if($isValidAddress) {
echo 'true is represented as ';
echo ($isValidAddress);
} else {
echo 'false is represented as ';
echo ($isValidAddress);
}
ผลลัพธ์จะแสดง: true is represented as 1
หากเปลี่ยนค่าตัวแปร $isValidAddress เป็น 0:
$isValidAddress = 0;
if($isValidAddress) {
echo 'true is represented as ';
echo ($isValidAddress);
} else {
echo 'false is represented as ';
echo ($isValidAddress);
}
ผลลัพธ์จะแสดง: false is represented as 0
สรุป
MySQL และ PHP จัดการค่า Boolean แบบเดียวกันคือ true = 1 และ false = 0 ทำให้การรวมระบบทั้งสองสอดคล้องกันอย่างสมบูรณ์