PHP中的位操作和MySQL检索 [英] Bit Manipulation and MySQL Retrieval in PHP
问题描述
我正在尝试对我的mysql表进行一些优化,以使表的管理更加容易.我想在位字段中存储用户权限.
I am trying to optimize my mysql table a little bit in order to have a slightly more manageable table. I would like to store user permissions in a bit field.
例如,用户权限可能是0110(我的用户权限数量越来越多,所以它的长度可能会更长)
For example, a users permissions could be 0110 (I have a growing number of user permissions, so the length of this could be a bit longer)
该示例可能对应于以下内容:
The example might correspond to the following:
0:用户无法在网站上发布新闻 1:用户可以在网站上发布新文章 1:用户可以在网站上编辑任何文章 0:用户无法从网站上删除文章 等等(其他权限)
0: User cannot post news items on the website 1: User can post new articles on the website 1: User can edit any article on the website 0: User cannot remove articles from the website etc. (for other permissions)
如果我将其存储在mysql位字段中.如何在PHP中进行操作?
If I have this stored in a mysql bit field. How can I manipulate this in PHP?
例如,在PHP中,有一种简单的方法来获取第3位并查看它是0还是1?
是否有一种简单的方法将第3位设置为0或1?
推荐答案
您可以使用按位运算符.
例如:
$bits = bindec('0110');
var_dump($bits & bindec('0100'));
在设置了$bits
中的第三位后,您将得到"4" (即非零-您可以将其视为确定").
Will get you "4" (i.e. non-zero -- which you can consider as "ok"), as the third bit in $bits
is set.
然后:
$bits = bindec('0010');
var_dump($bits & bindec('0100'));
将为您提供0-因为未设置$bits
中的第三位.
Will get you 0 -- as the third bit in $bits
is not set.
当然,不需要每次都调用bindec
-我只是在这里使用它来使事情更易于阅读;我的第一个示例可以这样重写:
Of course, no need to call bindec
each time -- I just used it here to make things easier to read ; my first example could be rewritten as something like this :
$bits = bindec('0110');
var_dump($bits & 1<<2);
为了使代码更易于理解,请不要使用这种不可思议的值,而应使用一些常量;例如:
And to make to code easier to understand, don't use such magic values, but use some constants ; for instance :
define('PERMISSION_TO_DO_X', 1);
define('PERMISSION_TO_DO_Y', 1<<1);
define('PERMISSION_TO_DO_Z', 1<<2);
并使用它们:
$bits = bindec('0110');
if ($bits & PERMISSION_TO_DO_X) {
echo "OK to do X<br />";
}
if ($bits & PERMISSION_TO_DO_Y) {
echo "OK to do Y<br />";
}
if ($bits & PERMISSION_TO_DO_Z) {
echo "OK to do Z<br />";
}
在这里,您可以得到这样的输出:
Which, here, gets you that kind of output :
OK to do Y
OK to do Z
因为:
- 最右边的位是0(未授予权限X)
- 第二位(从右开始)为1:授予Y权限
- 第三位(始终始终从右开始)为1:授予权限Z
这篇关于PHP中的位操作和MySQL检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!