也许你对我的自定义 is_unique 函数感兴趣。这里是。
您可以通过 2 种方式使用它:
1. is_unique[table_name.field_to_check.id_field_name.id_field_value] //<-- unique 1 field only
2. is_unique[table_name.field_to_check.id_field_name != 'id_field_value' and anotherIdName='theValue'] //<-- custom where
只需将此代码保存在一个文件中,将其命名为 MY_Form_Validation.php,并将其放在库目录下。然后你可以把那些 is_unique
public function is_unique($str, $field)
{
$result = true;
try {
if ($str) {//validate only if there's a value submitted
$is_query = 0;
$x = substr_count($field, '.'); //count of dots
//ex: is_unique[is_unique[$table_name.$field_name.$field_id!='$id' and 1=1]]
//ex: is_unique[$table_name.$field_name.id!='2' and name!='simson']
if($x == 2) {
list($table, $field, $where) = explode('.', $field);
$is_unique = 0;
if ($where) {
$logos = "select * from $table where $field =? and $where ";
} else {
$logos = "select * from $table where $field =? ";
}
$data = array($str);
$qq = $this->CI->db->query($logos, $data);
$is_query = 1;
$row = $qq->row();
$is_unique = !(bool)$row; //is_unique = (row == empty)
$result = (bool)$is_unique;
}
else {
if ($x >= 3) {
list($table, $field, $id_field, $id_val) = explode('.', $field);
$is_unique = 0;
if ($id_field && $id_val) {
$logos = "select * from $table where $field =? and $id_field != '$id_val' ";
} else {
$logos = "select * from $table where $field =? ";
}
$data = array($str);
$qq = $this->CI->db->query($logos, $data);
$is_query = 1;
$row = $qq->row();
if ($row) {
if ($row->id) {
if ($row->$id_field == $id_val) {
$is_unique = 1; //means editing it self, allow it
} else {
//already exists with different id
}
} else {
//used for left join table
}
} else {
$is_unique = 1; //does not exists
}
$result = (bool)$is_unique;
}
else if ($x == 1) {
list($table, $field) = explode('.', $field);
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
$is_query = 1;
$result = $query->num_rows() === 0;
}
}
if (is_log_query() && $is_query) {
$logos = "logos is_unique x==$x: " . $this->CI->db->last_query();
log_to_file($logos);
} else {
$logos = "logos is_unique x==$x: NOT EXECUTED";
log_to_file($logos);
}
}
}catch (Exception $e) {
die($e->getTraceAsString());
}
return $result;
}