Welcome Guest, Not a member yet? Register   Sign In
Bit value from MySQL
#1

[eluser]QUYET[/eluser]
Hi all,
I am new member from this forum and also new user of CodeIgniter. I am having trouble in converting bit value from MySQL to PHP boolean value.
Below is my code
<td>&lt;?php if($row['Suspend']==1){echo 'suspended';} ?&gt;</td>
Where $row['Suspend'] is data from MySQL and data type is bit.
Can anybody help?
#2

[eluser]KarlBallard[/eluser]
Why don't you just use TINYINT(1) as your field to store your value... That's all you need it for, correct?
#3

[eluser]mddd[/eluser]
I found some articles. They suggest that Mysql returns a BIT value not as a 0 or 1, but as some kind of binary data. Also, the behaviour changed somewhere in Mysql 5.

I recommend using a TINYINT in stead of a bit. You can store a 0 or 1 in the TINYINT and then it will work as you expect!
#4

[eluser]n0xie[/eluser]
Try:
Code:
&lt;?php if ( (bool) $row[‘Suspend’] === TRUE) {} ?&gt;

After digging into it a bit deeper you might want to turn this into an helper:
Code:
function mysql_bit($bit) {
return ord($bit) == 1;
}

Quote: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.

Source
#5

[eluser]QUYET[/eluser]
Thanks guys,
I should use tinyint as data type for the column. the ord fuction is quit complicated.
QUYET




Theme © iAndrew 2016 - Forum software by © MyBB