Advanced application of bit operation in PHP practical project

Time:2021-1-25

Let’s first look at the common requirements in a system

There is an advertisement table. We need to control the display of advertisements

  • Manual loading and unloading.
  • Only VIP view is allowed.

The possible table structure is as follows:

CREATE TABLE `finger_ad` (
  `ad_ id` int(11) unsigned NOT NULL AUTO_ Input comment 'primary key',
  `ad_ Name ` varchar (50) not null comment 'advertisement name',
  `ad_ image_ URL ` varchar (255) not null comment 'advertisement picture',
  `ad_ URL ` varchar (255) not null comment 'advertisement image URL jump address',
  `is_ VIP ` tinyint (1) not null default '0' comment 'is VIP display only',
  `Display ` tinyint (1) not null default '1' comment 'display status: 1 show, 0 hide',
  PRIMARY KEY (`ad_id`)
)Engine = InnoDB default chart = utf8 comment ='advertisement table ';

If later, we need to change. Several restrictions need to be added

  • Logged in user
  • User not logged in
  • Users not logged in within 30 days
  • Users registered for 30 days

Encounter the demand of this kind of restriction condition, development classmate is very troublesome?

Perhaps the first reaction of many developers is to add this new constraint field to the table structure. Everything seems to be fine.

Indeed, this is the fastest and easiest way to add fields. It can also meet our needs.

However, this will lead to the following problems:

  • Add restrictions each time. We all need to add fields. This kind of change to the database can change less. After all, unlimited addition of fields is not desirable.
  • If the amount of advertising table data is large. When it takes a few minutes to add a field, it will cause reading and writing pressure on the database server.
  • The more conditions there are, the longer the SQL conditional statements will be.

So, is there a better way to solve these problems?

Answer: Yes!

This is the advanced technique of bitwise and operators that we are going to talk about today.

Let’s change the table structure

DROP TABLE IF EXISTS `finger_ad`;
CREATE TABLE `finger_ad` (
  `ad_ id` int(11) unsigned NOT NULL AUTO_ Input comment 'primary key',
  `ad_ Name ` varchar (50) not null comment 'advertisement name',
  `ad_ image_ URL ` varchar (255) not null comment 'advertisement picture',
  `ad_ URL ` varchar (255) not null comment 'advertisement image URL jump address',
  `bit_ Condition 'int (11) unseigned not null comment' bit operation conditions: 1 - login accessible, 2 - not login accessible, 4-30 days registered accessible, 8-30 days not logged accessible, 16 - not consumed accessible, 32-vip accessible ',
  `Display ` tinyint (1) not null default '1' comment 'display status: 1 show, 0 hide',
  PRIMARY KEY (`ad_id`)
)Engine = InnoDB default chart utf8 comment ='advertisement table ';

We have removed all the conditions. Added a field:bit_condition 。 Combine all the conditions into one field.

So how do we write code at this time?

For example, we need to add ads with the following restrictions:

Only the login user or the user who has been registered for 30 days or the VIP user is allowed to access the advertisement.

So, what’s the significance of this advertisementbit_conditionHow to set the value? It’s very simple to add the bit values of these conditions directly. The value is: 37.

A lot can be strange. Set to 37, how can I know the sum of these values? If you are familiar with Linux system permissions, you can easily understand this approach. In fact, we use the character of bitwise sum operation: the value added by any combination will not be repeated.

This is difficult to understand. It’s hard for me to sort out three or two sentences. You can dig in-depth knowledge in this area on the Internet. You just need to know this feature.

So, how do we write SQL now?

Examples are as follows:

SELECT * FROM finger_ad WHERE display = 1 AND bit_condition & 3 = bit_condition

3 in this SQL statement corresponds to the value obtained by the current user for so many conditions. Ifbit_conditionThe bit value is and 3 by bit andbit_conditionThe results were the same, indicating that the conditions were met.

We solved all the conditions with one field. Thanks to the properties of bitwise and operators. At the same time, it’s also rightMySQLHappy to be able to support bitwise operators.

So what are its disadvantages?

It must have been seen by experienced students. This writing method can only satisfy the inclusion relation. If you want to meet three conditions at the same time, you can’t access it. Or, one satisfies the negation of the other.

The advantages are obvious, but the disadvantages are also obvious. We should choose according to the actual situation.

Extended learning file:

demo1';

//Defining constants
define('D1',1);
define('D2',2);
define('D3',4);
define('D4',8);
define('D5',16);

function showStatus($state){
    for($i= 1;$i<=5;$i++){
        $d = 'D'.$i;
        $DD = constant ($d); // take the value of the corresponding constant
        if(($state & $dd) > 0){
            Echo 'the first light is on; // 8
        }else{
            The light is off;
        }
    }
    Echo "SQL statement writing: select * from 'table' where state & {$state} = state;";
    echo '';
    echo '';
}
$state = D4;
Showstatus ($state); // only turn on the fourth light

$state = D1;
Showstatus ($state); // only turn on the first light

$state = D4 | D1;
Showstatus ($state); // turn on the first light and the fourth light

$state = (D4 | D2 | D1) & (~D1);
Showstatus ($state); // turn on the first light, the second light and the fourth light, and then turn off the first light
//Example 2
echo 'demo2';

/**
 *1. Permission application
 *Add up the values corresponding to the permissions you have
 *For example, if the moderator has permission (add, delete, modify, query), the permission value of the moderator is stored as 15 (8 + 4 + 2 + 1)
 *Then compare the sum of permission values with the actual permission value
 *If it turns out to be true, you have permission
 *If the result is false, there is no authority
 *
 *Note: permission value must be n power of 2, starting from 0 power, 31 power is 2147483648
 *The 32nd power is 4294967296, which has exceeded the maximum storage 4294967295 of commonly used int (10), so we must pay attention to the number of permissions (< 31)
 *Of course, if the storage format is bitint or varchar, which can store longer numbers, then the number of permissions can continue to increase
 */
//Grant permission value --- delete: 8, upload: 4, write: 2, read-only: 1
define('mDELETE',8);
define('mUPLOAD',4);
define('mWRITE',2);
define('mREAD',1);
//Vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//The authority of the Department Manager is (assuming that it has all the authority of the Department), | it is a bit or an operator. If you are not familiar with it, you can check the information
Echo'all permissions are: '(mdelete | mupload | mwrite | mread).'; // so add up the above permissions: 8 + 4 + 2 + 1 = 15

/*
*For example, if an employee has all the permissions except delete, what is the permission value?
*It should be: 4 + 2 + 1 = 7
*/

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//Judge whether someone's permission is available, and set the permission value in $key
/*
*The & bit and symbol are used to judge the authority,
*/
//If I only have upload and read permissions, then
$key = (mupload|mread); // it is equivalent to adding the upload and read-only permission values: 4 + 1 = 5
Echo 'the current permission is'. $key.';;
if($key & mDELETE){
    Echo 'has delete permission'
}else{
    Echo 'no delete permission'
}
if($key & mUPLOAD){
    Echo 'has upload permission'
} else{
    Echo'no upload permission '
}
if($key & mWRITE){
    Echo 'has write permission'
} else{
    Echo'no write permission '
}
if($key & mREAD){
    Echo 'has read-only permission.'; // 1
} else{
    Echo'no read-only permission '
}
?>

Results of operation:

Advanced application of bit operation in PHP practical project

 

For those interested in PHP back-end technology and PHP architecture technology, my official group is 1023755567Click here Learn together and discuss with each other.
There is already management in the group to sort out the knowledge system (source code, learning video and other materials). You are welcome to get it for free.

 

 

PHP advanced learning mind map, interview; free access to documents and video resources