Jump to content

Bitfields in PHP and MySQL


blueworld

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?
Link to comment
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!
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.