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:
<code class="php">$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();</code>
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.
The above is the detailed content of How to Use \'ON DUPLICATE KEY UPDATE\' with CodeIgniter\'s ActiveRecord Models?. For more information, please follow other related articles on the PHP Chinese website!