CodeIgniter - 在db中插入一个带有布尔值的新行

时间:2013-09-26 01:05:16

标签: codeigniter

当CodeIgniter将一行插入数据库时​​,它不会将PHP布尔值编码为MySQL所需的形式。

例如:

$new_record = array(
 "name" => "Don",
 "is_awesome" => true
);

这将进入MySQL:

name (varchar)   is_awesome (tinyint)
Don              0

任何人都知道处理这个问题的好方法吗?我一直在编写(is_awesome == true) ? 1 : 0;然后设置数组值,但这很糟糕。

2 个答案:

答案 0 :(得分:1)

您无法将truefalse添加到mysql中的TINYINT。你应该这样做10

$new_record = array(
"name" => "Don",
"is_awesome" => 1 //1 means it's true
);
$query = $this->db->insert('table_name', $new_record);

然后,当您提取时,将0视为false,将1视为true

<强>更新 您可以像这样创建一个名为tinyint_decode的函数:

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

}

通过这种方式,您可以通过传递0数组,通过您喜欢的任何内容来解释1$decode_set,无论是真,假,有效和无效,还是其他任何内容。

答案 1 :(得分:0)

MySQL没有布尔值。我通常做的是:

1) Have a field of length char(1) and say 'Y' or 'N'

OR

2) Have a numeric field and say '1' or '0'

提到的一种编码方法是唯一的方法。如果这是一个额外的步骤,我会在PHP代码本身中删除布尔值并使其成为'1-0'或'Y-N'