duplicate data insert in CodeIgniter
This is the Double Submit Problem.
There are several ways of dealing with it:
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.
Disable the submit button: Handles multiple clicks some of the time, but does not fix the user going back and submitting again.
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.)
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.
Unique transaction id: Described on this PHP hacks page, and on this answer.
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:
Generate a random
transaction_id
and put it in your web form. It goes along when the user clickssubmit
.When you receive the request to add a product, check for the
transaction_id
in the transaction table.If the id does not exist in the table, do the transaction, and insert the transaction_id into the table.
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
How to Subtract 24 Hour from Date Time Object in PHP
Using PHP, How to Insert Text Without Overwriting to the Beginning of a Text File
How to Validate Non-English (Utf-8) Encoded Email Address in JavaScript and PHP
PHP Xpath - Find Element with a Value and Also Get Elements Before and After Element
Attach Image to Facebook Event (PHP Sdk, Rest or Graph API)
Why Is My Database Backup Script Not Working in PHP
What Does the "&" Sign Mean in PHP
Facebook Oauthexception: "User Hasn't Authorized the Application to Perform This Action"
How to Get the First Day of the Week for the Current Locale? (Php/L8N)
Pdo's Rowcount() Not Working on PHP 5.2.6+
How to Merge 3 Images into 1 Image via PHP
Wordpress, Nginx Proxy and Subdirectory: Wp-Login.PHP Redirects to Domain
How to Store Variable Values Over Multiple Page Loads
Php: How to Load the Content of a Web Page into a Variable
Why Don't PHP and JavaScript's Timestamps Match