Using 'ON DUPLICATE KEY UPDATE' with CodeIgniter's ActiveRecord Models
In CodeIgniter models, you can use the standard insert method, but you need to manually add the "ON DUPLICATE KEY UPDATE" statement to the SQL query. Here's how you can achieve this:
$data = [
'name' => 'John Doe',
'age' => 30
];
// Create the insert string
$sql = $this->db->insert_string('users', $data);
// Append the "ON DUPLICATE KEY UPDATE" statement
$sql .= ' ON DUPLICATE KEY UPDATE duplicate=LAST_INSERT_ID(duplicate)';
// Execute the query
$this->db->query($sql);
// Get the insert ID
$id = $this->db->insert_id();
By adding the "ON DUPLICATE KEY UPDATE duplicate=LAST_INSERT_ID(duplicate)" statement, it ensures that when a duplicate key is encountered, the duplicate field is incremented while the insert is successful. The LAST_INSERT_ID() function allows you to retrieve the ID of the newly inserted row, even when an update occurs due to the duplicate key.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3