Duplicate Data Insert in Codeigniter

duplicate data insert in CodeIgniter

This is the Double Submit Problem.

There are several ways of dealing with it:

  1. The Post / Redirect / Get pattern: Breaks the back button, and it does not keep your user from going back far enough to submit again. Does not handle multiple clicks.

  2. Disable the submit button: Handles multiple clicks some of the time, but does not fix the user going back and submitting again.

  3. Store a token in the session: If you have multiple tabs open in the browser, the token stored in the session may get mixed up. (Note: It may be possible to create browser tab specific cookies using javascript, but I have not tried it myself.)

  4. Change the database to not allow duplicates: The best solution, but also the most effort. If it detects a set of duplicate data, ignore the second request.

  5. Unique transaction id: Described on this PHP hacks page, and on this answer.

  6. Multiple tokens in the session: A variation on option 3. If you store all generated tokens in the session, you don't need to involve the database. The probability of a duplicate is much lower, given that tokens are unique inside a session. Possible problems include the set of tokens growing out of control. Maybe fixable with a limited size stack where you add to the top of the stack, and extra tokens fall off the bottom. Untested.

--

I like the unique transaction id method. It works like this:

  1. Generate a random transaction_id and put it in your web form. It goes along when the user clicks submit.

  2. When you receive the request to add a product, check for the transaction_id in the transaction table.

  3. If the id does not exist in the table, do the transaction, and insert the transaction_id into the table.

  4. If the id does exist in the table, the transaction is already done.

You should also search for [double-submit-prevention] in to see if you can find an even better solution.

Prevent duplicate entry in Codeigniter

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;

Codeigniter: when I insert data I'm getting duplicate key error, how can I handle this error?

Either you check before, whether such user id exists already

$query = $this->db->get_where('user', array(
'id' => $user_id
));

$count = $query->num_rows();

if($count){
$this->session->set_flashdata('error', 'Such User exists. Please try again!');
redirect('controller_name/method_name');
}

// if above one does not evaluate true then insert
$this->db->insert('user', $some_array_with_data);

OR

try{

$this->db->insert('user', $some_array_with_data);

}catch(Exception $e){

// this is what you show to user,
$this->session->set_flashdata('error', 'Such User exists. Please try again!');

// if you want to log error then
log_message('error',$e->getMessage());

// redirect somewhere
redirect('controller_name/method_name');
}

While refreshing, duplicate data inserts into DB in codeigniter

Currently, There is no option to pass the status(success, error) messages to the overview page(or desired page).

Use the $_SESSION to holds the values and retrieve values from the session.

To show the status Message and avoid the duplicate entries, The code as follows:

CONTROLLER:

if (isset($_POST['save'])) {
$result = $this->home->insertEntry();
$message = ($result > 0) ? 'saved' : 'Not';
$this->session->set_userdata('message', $message);
//redirect, avoid duplicate entries
redirect('HomeController');
}

VIEW:

<div class="container sampleForm"><?php
if($this->session->has_userdata('message')){
echo $this->session->message;
$this->session->unset_userdata('message');
}

echo form_open( get_class(get_instance()) . '/insert')
. form_label('id') . form_input('id', isset($query['id']) ? $query['id'] : '', 'class="form-control"') . br()
. form_label('name') . form_input('name', isset($query['name']) ? $query['name'] : '', 'class="form-control"') . br()
. form_label('email') . form_custom_input('email','email', isset($query['email']) ? $query['email'] : '', 'class="form-control"') . br()
. form_submit('save', 'save', 'class="btn btn-primary"')
. form_close();
?> </div>


Related Topics



Leave a reply



Submit