What do bit flags in mysqli mean using fetch_field

2020-03-23 18:18发布

Using mysqli, I can get information about fields like so

$field = mysqli_fetch_field_direct($result, $fieldCount);

and I can get the field flags from the result using

$field->flags

The PHP manual says that this returns "An integer representing the bit-flags for the field." but that's all the info I can find. How can I interpret the bit flags? So far, I've worked out that

Integers (length of field doesn't matter) return the following bit flags depending on the attributes specified:

primary key 49967
primary & unique 53255
unique key 53251
foreign key 53257
unique & index 53259 (Auto increment 49675)

Thanks for any help you can offer!

1条回答
来,给爷笑一个
2楼-- · 2020-03-23 18:41

See comment at http://www.php.net/manual/en/mysqli-result.fetch-fields.php#101828

NOT_NULL_FLAG = 1                                                                             
PRI_KEY_FLAG = 2
UNIQUE_KEY_FLAG = 4                         
MULTIPLE_KEY_FLAG = 8
BLOB_FLAG = 16
UNSIGNED_FLAG = 32
ZEROFILL_FLAG = 64                    
BINARY_FLAG = 128                                       
ENUM_FLAG = 256
AUTO_INCREMENT_FLAG = 512
TIMESTAMP_FLAG = 1024
SET_FLAG = 2048
PART_KEY_FLAG = 16384
GROUP_FLAG = 32768
NUM_FLAG = 32768
UNIQUE_FLAG = 65536

Notice that every number posted above is a power of 2. (1 = 2^0, 2 = 2^1, 4 = 2^2 and so on). In other words, each of them corresponds to one bit in a number. To read what 49967 means, you can for example display it in binary form

>> decbin(49967);
'1100001100101111'

Starting from right, you can now read that the field has following flags

NOT_NULL 
PRI_KEY  
UNIQUE_KEY
MULTIPLE_KEY
UNSIGNED
ENUM
AUTO_INCREMENT
GROUP
UNIQUE

Other way to check, for specific flag is using binary conjunction operator & and mysqli constants as provided by nickb in comment below:

>> echo MYSQLI_NOT_NULL_FLAG & 49967
1
>> echo MYSQLI_PRI_KEY_FLAG & 49967
2
>> echo MYSQLI_UNIQUE_KEY_FLAG & 49967
4
>> echo MYSQLI_MULTIPLE_KEY_FLAG & 49967
8
>> echo MYSQLI_BLOB_FLAG & 49967
0

Basically you gat non-zero value for flags that are set, and 0 for flags that are unset. You can safely use it in conditions like this:

if($fieldFlags & MYSQLI_PRI_KEY_FLAG) {
  echo 'this field is a primary key';
}
查看更多
登录 后发表回答