Querying with ON DUPLICATE KEY UPDATE in CodeIgniter ActiveRecord
CodeIgniter's ActiveRecord provides a convenient method for interacting with the database. Users may encounter a scenario where they want to insert data into a table but also handle the case where a duplicate key exists. This situation can be addressed using the "ON DUPLICATE KEY UPDATE" clause.
To implement this clause within a CodeIgniter model, one can modify the raw SQL query. However, for a more integrated approach, consider the following method:
$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();
By appending the "ON DUPLICATE KEY UPDATE" clause to the insert string and using the query() method, the update clause will be executed when an attempt is made to insert data that already exists in the table.
This method allows for flexible database interactions while maintaining the convenience of ActiveRecord.
The above is the detailed content of How to Implement \'ON DUPLICATE KEY UPDATE\' with CodeIgniter ActiveRecord?. For more information, please follow other related articles on the PHP Chinese website!