Jump to content

Archived

This topic is now archived and is closed to further replies.

blueworld

Bitfields in PHP and MySQL

Recommended Posts

I'm trying to store some data to a bitfield column in MySQL 5, and then retrieve it back to an integer in PHP. Some part of the process isn't working, and I've been unable to find any helpful information in my searches.

Here's my test code:
[code]$query1 = "UPDATE phpbb_users SET warning1 = b'0101' WHERE user_id = 2";
mysql_query($query1);
$query = "SELECT warning1 FROM phpbb_users WHERE user_id = 2";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$bitfield = $row['warning1'];
echo gettype($bitfield);
echo '<br>' . $bitfield;
echo '<br>' . (int) $bitfield;[/code]
The column warning1 is of type BIT(32). Output of this script is [code]string

0[/code]
Does anybody know why I'm getting a string, and how I can get an integer?

Share this post


Link to post
Share on other sites
instead of the gettype() call, try

echo mysql_field_type($result, 0); // --> int

I'm guessing that db fields are retrieved as string representations of the contents

Share this post


Link to post
Share on other sites
Thanks! [code]echo mysql_field_type($result, 0);[/code] returns "unknown" for me. It doesn't seem to be a string representation.

I'm really puzzled by this. At this point it seems like it would be easier to just use integer fields instead of bit fields.

Share this post


Link to post
Share on other sites
if you try

var_dump($row['warning']);

you'll see it's a string in PHP - as I suspected - string representations are returned

Share this post


Link to post
Share on other sites
According to the MySQL manual,
[quote]BIT[(M)]

A bit-field type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M is omitted.

This data type was added in MySQL 5.0.3 for MyISAM, and extended in 5.0.5 to MEMORY, InnoDB, and BDB. Before 5.0.3, BIT is a synonym for TINYINT(1). [/quote]

You're right, it was being returned as a string. The binary data was being interpreted as ascii encoding, so I got 4 characters for my 32-bit field. I guess I have to write a function now to convert the characters into an appropriate integer.

Thanks for your help!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.