php 如何向 MySQL 添加布尔字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3931023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a Boolean field to MySQL?
提问by Trufa
It seems I should use tinyint(); but I don't know how to implement it?
看来我应该使用 tinyint(); 但我不知道如何实现它?
The question is what is your recommendation if I need to have a boolean field in MySQL DB and modify it′s value with PHP
问题是如果我需要在 MySQL DB 中有一个布尔字段并用 PHP 修改它的值,你的建议是什么
回答by Felix Kling
Yep, TINYINT(1)
is the way to go... you can also use BOOL
or BOOLEAN
which are synonyms (so it does not make a difference).
TINYINT(1)
是的,是要走的路......你也可以使用BOOL
orBOOLEAN
which 是同义词(所以它没有区别)。
0
evaluates to false
in PHP and 1
to true
(actually, any other number than 0
evaluates to true
, but 1
is normally used).
0
false
在 PHP 中计算为1
to true
(实际上,除了0
计算为之外的任何其他数字true
,但1
通常使用)。
回答by Muktadir
I prefer none of bool, BIT, TINYINT(1). because none of them are actually boolean. You can check the following link for 'why':
我不喜欢 bool、BIT、TINYINT(1)。因为它们实际上都不是布尔值。您可以查看以下链接以了解“为什么”:
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
I would better use : ENUM ('false', 'true') not null - as datatype. You can pass 'true' or 'false' (as strings) from PHP. And it will take only 1 byte to store it!
我最好使用: ENUM ('false', 'true') not null - 作为数据类型。您可以从 PHP 传递 'true' 或 'false'(作为字符串)。并且只需要 1 个字节来存储它!
回答by Matthew Flaschen
You're correct that the general solution is tinyint(1)
. You can use BOOL for short:
您是正确的,一般解决方案是tinyint(1)
. 您可以使用 BOOL 简称:
CREATE TABLE example (
flag BOOL
);
回答by Haim Evgi
you have option of tinyint(1) or bit
您可以选择 tinyint(1) 或 bit
insert 0 or 1 to this field
在此字段中插入 0 或 1
see this post of the difference :
看这个帖子的区别:
回答by tormuto
I think since you actually want to enforce a boolean (0,1) constraint on a mysql table field, the best shot is uning enum
我认为由于您实际上想对 mysql 表字段强制执行布尔 (0,1) 约束,因此最好的方法是 uning enum
CREATE TABLE table_name(
boolean_field_name ENUM('0', '1')
);