CodeIgniter's ActiveRecord provides a convenient way to insert data into the database. However, for cases where data being inserted may conflict with existing records, it may be necessary to specify an "ON DUPLICATE KEY UPDATE" clause to handle such scenarios.
In CodeIgniter's ActiveRecord-based models, you can append the "ON DUPLICATE KEY UPDATE" clause to your insert operation by adding:
<code class="php">$sql = $this->db->insert_string('table', $data) . ' ON DUPLICATE KEY UPDATE duplicate=LAST_INSERT_ID(duplicate)'; $this->db->query($sql);</code>
This statement adjusts the generated SQL so that when inserting data into the "table", if there's an existing record with the same key, the "duplicate" field will be incremented instead of causing an error.
The above is the detailed content of How can I use \'ON DUPLICATE KEY UPDATE\' in CodeIgniter\'s ActiveRecord models?. For more information, please follow other related articles on the PHP Chinese website!