Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-10-23 14:08:02
Original
468 people have browsed it

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:

<code class="php">$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();</code>
Copy after login

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.

The above is the detailed content of How to Use \'ON DUPLICATE KEY UPDATE\' with CodeIgniter\'s ActiveRecord Models?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
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!