Ok, if you subscribe to my blog for personal reasons, this isn’t very relevant to you, but for those of you here for the programming, on a recent project I had some problems getting the BIT field in MySQL to be interpreted as a boolean in PHP. There are a couple of discussions on the net about it here and here, but I couldn’t find any simply stated solutions on the net. So here’s what I ended up doing. You can also download the file here, rename the file .php to use it.

function mysql_bit($bit) {
return ord($bit) == 1;

Reader Comments

  1. A boolean is a variable that evaluates as true or false. A BIT in MySQL is a number that is only 1 bit long. a 32bit number goes as high as 4,294,967,295, but a 1 bit number only goes as high as 1. So it has 2 values 0 and 1, which is almost a boolean 0 = false, 1 = true.

    Unfortunately when PHP reads a BIT from MySQL into PHP variable, it seems to treat it as a ASCII string character that is represented by the number 0 or 1. In ASCII the letter A has the value 65, B 66, etc.

    The ord() function in MySQL will convert from a number to the ASCII equivilant. For example ord(65) = A, etc. So I used the ord function to convert the number 0 or 1 to the ASCII equivilant and then compare with the BIT returned from MySQL.

  2. PHP is pretty much a clone of Perl. You’d probably offend a number of Python yahoo’s by saying PHP is like Python.

    I could go into specifics, like Python uses Optimized C in it’s cold and strict heart, while perl, is just a hacker language.

    By the way, .net has Regex. Most modern languages do.

  3. Try this instead:

    function mysql_bit($bit) {
    if(ord($bit) == 1)
    return 1;
    return 0;

    MySQL bit = 0/false…this returns 0, 1/true returns 1.

    Happy Days.

  4. Nice one for posting this.

    Although I do like those cute ascii representations, a functioning class is more useful to me innit.


Write a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.