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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Checking for Duplicate Values in CodeIgniter

When building a registration or settings form, you often need to ensure that unique identifiers don't clash with existing records. In CodeIgniter, handling this logic requires bridging the gap between the standard validation engine and raw database queries. The goal is straightforward: validate that rolekey is present and clean, then verify it doesn't already exist in the database before allowing the insert to proceed.

CodeIgniter's form validation rules handle format checks like trimming and XSS cleaning well, but they don't natively support "database existence" checks directly within the rule string itself. You cannot simply append a custom check to required|xss_clean that queries the table without writing custom logic. The standard approach is to perform the existence check outside the validation rules array, using the database query builder or active record methods, and then manually trigger a validation failure if the value is taken.

Here is how you can structure this in your controller:

First, configure your standard rules as usual. You want rolekey to be trimmed and required, with XSS filtering applied:

$this->form_validation->set_rules('rolename', 'Role Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('rolekey', 'Role Key', 'trim|required|xss_clean');

Once these rules are set, load your database library if it hasn't been loaded automatically via $this->load->database(). Then, execute a query to check for duplicates. Assuming you have a model or direct access to the database connection, you can write a simple SELECT statement:

$this->db->where('rolekey', $this->input->post('rolekey'));
$query = $this->db->get('roles'); // Adjust table name as needed

If the query returns any rows ($query->num_rows() > 0), the value exists. At this point, you must force the validation engine to fail for that specific field. You can do this by setting a custom error message on the form validation instance:

if ($query->num_rows() > 0) {
    $this->form_validation->set_message('rolekey', 'A role with this key already exists.');
    $this->form_validation->run(); // Re-run to trigger the error
} else {
    // Proceed with insert logic here
}

Alternatively, if you prefer a cleaner flow without re-running validation immediately, you can manually check validation_errors() after your standard rules run. If the database check fails, you can stop execution and redirect the user:

if (!$this->form_validation->run()) {
    // Check for duplicate here before showing errors if needed
}

One critical pitfall to watch out for is race conditions. If your application supports high concurrency, a simple "check then insert" pattern can still fail if two requests arrive simultaneously with the same rolekey. Both might see an empty result set, pass their checks, and try to insert, resulting in a database constraint violation (like a unique index error).

To handle this robustly, you should define a unique index on your rolekey column in your database schema. This ensures that even if two processes think the value is free, the database will reject the second insert instantly. You can then catch the specific exception or error code returned by your database driver and provide a user-friendly message like "The role key you entered is already in use."

While CodeIgniter handles this logic well, developers coming from other frameworks might find the separation of validation rules and database queries slightly less integrated than in Laravel. However, this modular approach gives you fine-grained control over error messages and allows you to hook into specific events without rewriting the entire validation engine. If you are ever looking for a framework where such checks feel more native or where you might need to migrate similar logic, platforms like https://laravelcompany.com offer robust query scopes that simplify this exact pattern, but sticking to CodeIgniter's active record methods keeps your codebase lightweight and consistent with the existing architecture.

Remember that xss_clean is deprecated in newer versions of CodeIgniter (version 4+). If you are upgrading, ensure you replace it with native PHP sanitization or the updated security utilities provided by the framework to avoid security warnings or unexpected behavior in production environments.

Our network