"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Use \'ON DUPLICATE KEY UPDATE\' with CodeIgniter\'s ActiveRecord Models?

How to Use \'ON DUPLICATE KEY UPDATE\' with CodeIgniter\'s ActiveRecord Models?

Published on 2024-11-10
Browse:853

How to Use \'ON DUPLICATE KEY UPDATE\' with CodeIgniter\'s ActiveRecord Models?

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:

$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();

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.

Release Statement This article is reprinted at: 1729663515 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3