What do bit flags in mysqli mean using fetch_field_direct

前端 未结 1 982
不知归路
不知归路 2021-01-13 07:32

Using mysqli, I can get information about fields like so

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

and I can get the field

相关标签:
1条回答
  • 2021-01-13 08:11

    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';
    }
    
    0 讨论(0)
提交回复
热议问题