2014-06-24 69 views
0

我正在檢查值是否唯一。我有這個功能,但是如何再次檢查。Codeigniter - 檢查值是否唯一

這是函數(它的工作):

public function is_unique($field, $val) 
    { 
     $this->db->select($field)->where($field, $val); 
     $result = $this->get(); 
     $result = $result['data']; 

     return $bool = count($result) == 0 ? $val : FALSE; 
    } 

這是我檢查的價值,看它是否是獨一無二的:

$unique_code = random_string('alnum', 6); 
$unique_code = $this->posts->is_unuque('unique_code', $unique_code) != FALSE ? $unique_code: random_string('alnum', 6); 

如何創建IF函數新價值返回FALSE並檢查新值(使循環直到值是唯一的)?

回答

0

試試這個;

function is_unique($field, $val = null) 
{ 
     if (is_null($val)) 
     { 
       // No $val supplied, so we generare a new one. 
       $val = random_string('alnum', 6); 
     } 

     $this->db->select($field)->where($field, $val); 
     $result = $this->db->get('table'); 

     if ($result->num_rows() > 0) 
     { 
       // Found a match 
       // Try again.... 
       $this->is_unique($field); 
     } 
     else 
     { 
       // No match 
       return $val; 
     } 
} 

如果不提供$ val,則該函數將生成一個新的隨機字符串,然後檢查它是獨一無二的。如果不是,它會再次嘗試。

0
return (count($result) == 0 ? $val : $this->is_unique($filed,random_string('alnum', 6)); 

可能是這樣的而不是返回false運行功能,直到結果是唯一

$unique_code = $this->posts->is_unuque('unique_code', $unique_code);