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;
}
ahahah i already got this via your feed… but yeah very cool. you could of course use a proper programming language like java or .net, and be done with all these pedantic issues… :P ehehehe
glad to be tagged though :)
PHP is great for somethings though, its fast to write websites in, and anything that processes text. Regex FTW !!!
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.
o.o me is confuzzled. haha! I think I know what a boolean is… >.<
Ahhh, cool. o.O MySQL and PHP are different languages, right?
Yea, MySQL is a language for create and querying databases. PHP is a scipting language similar to python.
Oooh, cool.
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.
thanks, I forgot about the ord function.
Thanx mate…… :D
Try this instead:
function mysql_bit($bit) {
if(ord($bit) == 1)
return 1;
else
return 0;
}
MySQL bit = 0/false…this returns 0, 1/true returns 1.
Happy Days.
Nice one for posting this.
Although I do like those cute ascii representations, a functioning class is more useful to me innit.
:)
This was very helpful. Thank you for sharing!
Thanks for this tip, really made my day
Thanks for the tip! Just wait till php 9 comes out! LOL
Tons of thanks for the tip. very helpful