CodeIgniter MySQL Update Data

Updating data is an essential part of any web application.

In CodeIgniter, we can update records using:

  1. Query Builder (Active Record) – easy & secure
  2. Raw SQL Queries – manual way

🔹 Step 1: Load Database

Ensure your database is connected:

$autoload['libraries'] = array('database');

Or load manually in your controller:

$this->load->database();

🔹 Step 2: Update Data Using Query Builder

class UpdateController extends CI_Controller {

    public function update_user($id) {
        $data = array(
            'name'  => 'Updated Name',
            'email' => 'updated@example.com'
        );

        $this->db->where('id', $id);   // WHERE id = ?
        $this->db->update('users', $data); // UPDATE users SET name=?, email=? WHERE id=?

        if ($this->db->affected_rows() > 0) {
            echo "User updated successfully!";
        } else {
            echo "No changes made!";
        }
    }
}

👉 URL Example:

http://your-site/index.php/updatecontroller/update_user/1

🔹 Step 3: Update with Multiple Conditions

public function update_status() {
    $data = array('status' => 1);

    $this->db->where('status', 0);
    $this->db->where('email LIKE', '%@example.com');
    $this->db->update('users', $data);

    echo $this->db->affected_rows() . " users activated.";
}

🔹 Step 4: Update with Limit (Raw SQL)

CodeIgniter’s Query Builder does not support LIMIT in updates, but you can use raw SQL:

public function update_limit() {
    $sql = "UPDATE users SET status = 1 WHERE status = 0 LIMIT 5";
    $this->db->query($sql);

    echo "Limited update applied!";
}

🔹 Step 5: Update Using Form Input

public function update_from_form() {
    $id    = $this->input->post('id');
    $name  = $this->input->post('name');
    $email = $this->input->post('email');

    $data = array(
        'name'  => $name,
        'email' => $email
    );

    $this->db->where('id', $id);
    $this->db->update('users', $data);

    echo "User updated from form input!";
}

🔹 Example Output

Before update:

ID: 1 | Name: John Doe | Email: john@example.com

After update:

ID: 1 | Name: Updated Name | Email: updated@example.com



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.