Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check multiple values to be unique in CodeIgniter

I've a html form that is used for registration of users. I want to apply a condition in codeIgniter that if someone writes 2 input fields(firstname and lastname) that already exists in database then don't allow to insert the data. Like I can write

$this->form_validation->set_rules('firstname', 'First Name', 'required|is_unique[student.firstname]');
$this->form_validation->set_rules('lastname', 'Last Name', 'required|is_unique[student.lastname]');

How to apply on both? Like both should be unique but one can already exist. I want something like "Combined unique value"

Example:

First Name: Ali

Last Name: Mohyudin

If someone writes again the same in both fields then I don't want to insert data in database but if someone writes something like:

First Name: Ali

Last Name: Imran

then I should accept the user.

like image 241
azher ishfaq Avatar asked Dec 24 '22 16:12

azher ishfaq


1 Answers

You can do it using callback in validation

$this->form_validation->set_rules('firstname', 'First Name', 'required|callback_check_user');// call callback function

$this->form_validation->set_rules('lastname', 'Last Name', 'required');

Check combination for first name and last anme

function check_user() {
    $first_name = $this->input->post('firstname');// get first name
    $last_name = $this->input->post('lastname');// get last name
    $this->db->select('user_id');
    $this->db->from('student');
    $this->db->where('firstname', $first_name);
    $this->db->where('lastname', $last_name);
    $query = $this->db->get();
    $num = $query->num_rows();
    if ($num > 0) {
        return FALSE;
    } else {
        return TRUE;
    }
}
like image 180
Saty Avatar answered Dec 27 '22 20:12

Saty