![](/img/trans.png)
[英]What is the best way to store multiple checkbox values in the database and work with it later on
[英]What's the best way to store Checkbox Values in MySQL Database?
首先,以这个页面为例:点击这里
如果您查看“设施”部分,则有 3 组复选框(单元功能、社区功能和租金中包含的实用程序)。
我的问题是:如何使用 PHP 制作 3 个数组变量(例如 $unit_features、$community_features 和 $utilities_included)来存储哪些框是/未检入表中的 3 个相应字段?
更重要的是:如何以相同的数组格式从表中提取数据,以便查看/编辑/删除细节?
属性和便利设施之间存在多对多关系。 到 model 这个,你需要一个单独的表,而不是可变数量的列。
有一张表可以存储您的属性。
INSERT INTO property (id, address, square_footage...) VALUES (111, '123 Main St', 1234...)
有一张桌子可以存放所有可能的便利设施。
INSERT INTO amenities (id, type, description) VALUES (222, 'Unit Features', 'Air Conditioning');
对于属性的每个便利设施,在与这两个相关的表中插入一行:
INSERT INTO property_amenitities (property_id, amenity_id) VALUES (111, 222);
如果您想知道特定属性具有哪些便利设施,只需SELECT
此表中的所有行即可获取该属性的键。 当您想打印所有便利设施的复选框时, SELECT
从amenities
表中,并对property_amenities
表执行LEFT OUTER JOIN
。 property_amenities
表中具有 null 值的那些行是未选中的框。
相关阅读。 你应该从当地的 BORDERS 那里拿起一本关于关系数据库的书,然后他们 go 倒闭了:)
如果它们不是相互排斥的; 您可以使用按位运算符来存储它们。
field = 0;
if($unity_features_selected == true) {
field |= (1<<0);
}
if($community_features_selected == true) {
field |= (1<<1);
}
if($utilties_included_selected == true) {
field |= (1<<2);
}
然后将字段存储为无符号整数。 这使您可以查询(例如 unity_features),例如
select * from <table> where field&(1<<0);
或社区功能:
select * from <table> where field&(1<<1);
1) php serialize and unserialize ( http://php.net/manual/en/function.serialize.php ) will help you keep arrays or objects or any other structural data in db.
2)使用数组格式输入名称,如下所述: Submitting a multidimensional array via POST with php
3)请记住,未选中的复选框根本不会发送,因此请始终为每个复选框字段创建一个隐藏的输入字段。 这将确保未选中的复选框将作为假发送。 这是一个示例: 发布未选中的复选框
如此令人欣慰 - 您可以通过 arrays 的方式发送所有复选框(1 或 0),并将它们作为序列化对象存储在三个字段中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.