Home > Database > Mysql Tutorial > body text

How to Implement \'ON DUPLICATE KEY UPDATE\' with CodeIgniter ActiveRecord?

Barbara Streisand
Release: 2024-10-28 22:34:02
Original
190 people have browsed it

How to Implement

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!