我正在尝试检查值是否唯一。我有这个功能,但我怎么能再检查一遍呢。
这是功能(它正在工作(:
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);
如果函数返回FALSE并检查新值(循环直到值是唯一的(,我如何创建新值?
试试这个;
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,函数将生成一个新的随机字符串,然后检查它是否唯一。如果不是,它会再试一次。
return (count($result) == 0 ? $val : $this->is_unique($filed,random_string('alnum', 6));
可能是这样的,而不是返回错误的运行函数,直到结果是唯一的
$unique_code = $this->posts->is_unuque('unique_code', $unique_code);