CodeIgniter - Checking to see if a value already exists in the database

you can always just add

$this->form_validation->set_rules('username','Username','is_unique[users.username]');

where user.username is the table.column


You just edit your validation rule

$this->form_validation->set_rules('rolename', 'Role Name', 'trim|required|xss_clean|is_unique[table_name.rolename]'); 

If you want to make your validation function available in more than one controller, you should include the rule in a MY_Form_validation library.

I do this in MY_Form_validation:

function exist($str, $value){       

  list($table, $column) = explode('.', $value, 2);    
  $query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = $str'");
  $row = $query->row();

  return ($row->count > 0) ? FALSE : TRUE;

}

Then in your model (or controller) when you set your rules:

$this->form_validation->set_rules('username','username','exist[users.user_name]');

The rule calls the exist function.

The exist function explodes the string users.user_name at the dot and then queries the database to see if a record is returned. If it does, return false, else true. The rule will fail on a false return.


There is not a built-in form validation check for whether or not a value is in the database, but you can create your own validation checks.

In your controller, create a method similar to this:

function rolekey_exists($key)
{
    $this->roles_model->role_exists($key);
}

And in your model that handles roles, add something like this:

function role_exists($key)
{
    $this->db->where('rolekey',$key);
    $query = $this->db->get('roles');
    if ($query->num_rows() > 0){
        return true;
    }
    else{
        return false;
    }
}

And then you can write a form validation check like this:

$this->form_validation->set_rules('username', 'Username', 'callback_rolekey_exists');

See this page for more information:

https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

Tags:

Codeigniter