Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - Insert a new row in db with a boolean value

Tags:

codeigniter

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.

like image 760
Don P Avatar asked May 07 '26 09:05

Don P


1 Answers

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.

like image 162
cg.mike Avatar answered May 09 '26 05:05

cg.mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!