Mahdi Mahdi - 6 months ago 9
PHP Question

To deal with 'Boolean' values in PHP & MySQL

Currently I'm using

Tinyint(1)
to indicate
Boolean
values in my MySQL databases, which I really don't like that. So, how could I store and retrieve
Boolean
values in my
MySQL
databases via
PHP
?

How to use it in
WHERE
clause and how to assign the value in
INSERT, UPDATE
queries properly?

When I have it back on PHP, it's
TRUE
,
true
, or simply
1
, if I'm gonna check that with
===
?

Also did you ever had any problem when you migrating from
Tinyint(1)
to
BOOLEAN
?

Thanks in advance. :)

Update:

I know that
Tinyint(1)
is the same as
Boolean
, however I want to work on
Boolean
data type instead of
Tinyint(1)
. That's why I'm asking the question.

Answer

MySQL doesn't have a boolean data type. Tinyint(1) is pretty close enough. Working with this in PHP is simple.

If (1) echo 'true'; // is the same as if (true)
// Just as
if (0) echo 'false'; // is the same as if (false)

And if you really really want a boolean value, you can do

// $mysql_data is tinyint value from db
$boolean = $mysql_data ? true : false;
// Now you have your boolean as $boolean
Comments