Question

I'm implementing a bitfield column to my database on my current project. It's 50 bits long but it does not seem to properly insert the bitfield I create in PHP. This is the literal query (I tried submitting it both in PHP and in phpMyAdmin).

 INSERT INTO features (title, category_id, bitnum) 
 VALUES ("a6", "0", b'00000000000000000000000000100000000000000000000000')

But the value which phpMyAdmin and PHP outputs for some reason is this:

00001100110011100000111000001101100011000000111000

Now, if I choose to select the bitnum column using BIN(bitnum) in a SELECT-query it outputs the correct value. But before I proceed with this I need to know if I'm actually doing this right (because I need to check the column against flags later on). It doesn't seem right that the first bitfield I insert, having only one 1 in the middle, becomes a weird mess of 0 and 1s which right now don't make any sense to me.

I wasn't able to find anything on the subject on Google, nor SO. To my understanding the BIT column supports up to 64 bits.

Thanks in advance.

Was it helpful?

Solution

Is your bitnum column defined as bit(50)?

My guess is that the value gets inserted properly into DB. Everything after that requires some testing.

Do you use some query when you say "phpMyAdmin and PHP outputs for some reason is this: 00001100110011100000111000001101100011000000111000"?

I tried to use the PhpMyAdmin a little but it displays bit colums as empty, NULL or whatever. Even using PhpMyAdmin's SQL query interface didn't reveal the values as they should appear. Try some other DB management software. I use Sequel Pro and it shows the bit values as they are entered into DB. (Maybe PhpMyAdmin does it too somehow, I just don't know how.)

As for PHP engine, well... See my interesting question. There might be a bug in some PHP version or not. At least a query similar to this should retrieve a correct value.

SELECT (bitnum + 0) AS my_multiple_bit FROM features

This was my RTM moment of that question: If "+ 0" is not used the value of a bit(1) column is treated as binary string. (Also remember that PHP version can cause it's own problems.)

Maybe also BIN(bitnum) works as (bitnum + 0). Try and test with one more PHP engine versions. If everything works, well... then everything works.

BTW. Is there some specific reason in using bit(50) column? What's wrong with int or char? (I used bit(1) as a boolean true/false just for the kick of it. tinyint(1) is my other alternative fo booleans. I didn't read this whole article but maybe bit columns aren't the best choice for column type in MySQL.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top