Reputation: 63718
When CodeIgniter is inserting a row into a DB, it doesn't encode PHP booleans into a form MySQL needs.
For example:
$new_record = array(
"name" => "Don",
"is_awesome" => true
);
This will enter into MySQL as this:
name (varchar) is_awesome (tinyint)
Don 0
Anyone know a good way to deal with this? I've been writing (is_awesome == true) ? 1 : 0;
then setting the array value, but that sucks.
Upvotes: 3
Views: 3611
Reputation: 191
you can't add true
or false
to a TINYINT
in mysql. you should do 1
or 0
like this
$new_record = array(
"name" => "Don",
"is_awesome" => 1 //1 means it's true
);
$query = $this->db->insert('table_name', $new_record);
then just when you fetch it consider 0
as false
and 1
as true
Update:
you can create a function called tinyint_decode
like this:
public function tinyint_decode($result = array(), $decode_set = array())
{
//$result is what you got from database after selecting
//$decode_set is what you would like to replace 0 and 1 for
//$decode_set can be like array(0=>'active', 1=>'inactive')
//after fetching the array
$result->is_awesome = ($result->is_awesome == 1 ? $decode_set[1] : $decode_set[0]);
return true;// or anything else
}
this way you can interpret 0
and 1
by anything you like whether it's true and false, active and inactive, or anything else just by passing $decode_set
array.
Upvotes: 1
Reputation: 3128
MySQL doesn't have boolean values. What I usually do is:
1) Have a field of length char(1) and say 'Y' or 'N'
OR
2) Have a numeric field and say '1' or '0'
The one method to encode you mentioned is the only way to do it. If it's an extra step, I would just get rid of boolean in the PHP code itself and make it a '1-0' or 'Y-N'
Upvotes: 0