phpcodeigniteractiverecordsql-insertmysql-error-1062

Prevent duplicate entry in Codeigniter


How to prevent duplicate entry in codeigniter? Following is the code:-

$params = array('value1' => 'test_value', 'value2' => 'test_value');
$this->db->insert('table_name',$params);

Solution

  • 2 ways to prevent duplicate entry insertion into the database,

    METHOD 1

    You can use $this->form_validation->set_rules in the controller file and you can validate your input values,

    Example :

    In Controller

    $this->form_validation->set_rules('value1', 'value1 field label', 'trim|required|xss_clean|is_unique[table_name.value1]');
    $this->form_validation->set_rules('value2', 'value2 field label', 'trim|required|xss_clean|is_unique[table_name.value2]');
    $this->form_validation->set_message('is_unique', '%s is already exists');
    if ($this->form_validation->run() === TRUE){
        // load your model function here
        $this->model_name->insert();
    }
    

    In Model

    public function insert(){
        $postdata = $this->input->post();  
        extract($postdata);
        $this->db->insert('table_name', compact('value1','value2'));
        return ($this->db->trans_status()) ? $this->db->insert_id() : false;
    }
    

    METHOD 2

    Validating values in model file before insert

    $params = array('value1' => 'test_value', 'value2' => 'test_value');
    extract($postdata);
    if($this->db->limit(1)->get_where('table_name', compact('value1'))->num_rows() === 0 && $this->db->limit(1)->get_where('table_name', compact('value2'))->num_rows() === 0){
        $this->db->insert('table_name', $params);
    }
    return ($this->db->trans_status()) ? $this->db->insert_id() : false;