2014-06-24 49 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);