Applying ON DUPLICATE KEY UPDATE in CodeIgniter Models
Q: I'm working with a CodeIgniter model and want to insert data into the database. How can I implement the ON DUPLICATE KEY UPDATE statement, which I used in my original SQL queries, within the ActiveRecord model?
A: CodeIgniter provides a workaround to add the "ON DUPLICATE" statement to your queries without modifying its core files. Here's how:
<code class="php">$sql = $this->db->insert_string('table', $data) . ' ON DUPLICATE KEY UPDATE duplicate=LAST_INSERT_ID(duplicate)'; $this->db->query($sql); $id = $this->db->insert_id();</code>
By executing this custom SQL statement, you can insert data into the database and update the duplicate counter if the key already exists.
The above is the detailed content of How to Implement ON DUPLICATE KEY UPDATE in CodeIgniter Models?. For more information, please follow other related articles on the PHP Chinese website!