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.
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: 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)
If I have this stored in a mysql bit field. How can I manipulate this in PHP?
For example, in PHP is there an easy way to get the 3rd bit and see if it is a 0 or a 1?
Is there an easy way to set the 3rd bit to be a 0 or a 1?
You can use bitwise operators.
For instance :
Will get you “4” (i.e. non-zero — which you can consider as “ok”), as the third bit in
$bitsis set.And :
Will get you 0 — as the third bit in
$bitsis not set.Of course, no need to call
bindeceach time — I just used it here to make things easier to read ; my first example could be rewritten as something like this :And to make to code easier to understand, don’t use such magic values, but use some constants ; for instance :
And to use them :
Which, here, gets you that kind of output :
Because :