2013-09-26 18 views
3

當CodeIgniter向數據庫中插入一行時,它不會將PHP布爾值編碼爲MySQL需要的格式。CodeIgniter - 在數據庫中插入一個帶有布爾值的新行

例如:

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

這將進入MySQL作爲本:

name (varchar) is_awesome (tinyint) 
Don    0 

任何人都知道一個很好的方法來處理這個?我一直在寫(is_awesome == true) ? 1 : 0;然後設置數組值,但這很糟糕。

回答

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」

+0

使用「Y」或「N」的1個字符的mysql列是一個可怕的想法。任何時候你返回這一行,並檢查大多數語言,如果它是真或假,你會得到真正的字符串存在。 –

+0

也看起來像MySQL有一個布爾類型:http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html 也許我應該使用 –

+0

是的你是對的關於1字符thingy。我通常做1和0. –

1

你不能在mysql中添加truefalseTINYINT。你應該做10這樣

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

則只是當你把它拿來考慮0false1作爲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 

} 

這樣你就可以解釋t 01由你喜歡的任何東西,無論是真的還是假的,活動的還是非活動的,或者只是通過傳遞$decode_set數組。

+0

感謝邁克,但這並沒有回答我的問題,關於如何跳過從「真」和「假」編碼爲1或0的步驟 –

+0

我會更新我的答案,情況:) –

+0

它已更新。看看它。但不要忘記在處理之前使用foreach或其他任何其他方法獲取結果,否則您將錯誤地使用stdClass。 –

相關問題