CodeIgniter MySQL Insert Data

After creating a database and table, the next step is to insert data.

In CodeIgniter, you can insert records using:

  1. Active Record (Query Builder) – recommended, easy & secure.
  2. Raw SQL Queries – direct SQL commands.


🔹 Step 1: Load Database

Make sure database is loaded. Add this in autoload.php:

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

Or load it manually:

$this->load->database();


🔹 Step 2: Insert Data using Query Builder

Example: Insert into users table

class InsertController extends CI_Controller {

    public function insert_user() {
        // Sample data
        $data = array(
            'name'  => 'John Doe',
            'email' => 'john@example.com',
            'created_at' => date('Y-m-d H:i:s')
        );

        // Insert data
        if ($this->db->insert('users', $data)) {
            echo "User inserted successfully!";
        } else {
            echo "Failed to insert user.";
        }
    }
}

👉 URL:

http://your-site/index.php/insertcontroller/insert_user


🔹 Step 3: Insert Multiple Records

public function insert_multiple() {
    $data = array(
        array(
            'name' => 'Alice',
            'email' => 'alice@example.com',
            'created_at' => date('Y-m-d H:i:s')
        ),
        array(
            'name' => 'Bob',
            'email' => 'bob@example.com',
            'created_at' => date('Y-m-d H:i:s')
        )
    );

    if ($this->db->insert_batch('users', $data)) {
        echo "Multiple users inserted!";
    } else {
        echo "Failed to insert multiple records.";
    }
}


🔹 Step 4: Insert Data using Raw SQL

public function raw_insert() {
    $sql = "INSERT INTO users (name, email, created_at) VALUES (?, ?, ?)";
    $this->db->query($sql, array('Charlie', 'charlie@test.com', date('Y-m-d H:i:s')));
    echo "User inserted with raw SQL!";
}


🔹 Step 5: Get Last Inserted ID

$this->db->insert('users', $data);
$insert_id = $this->db->insert_id();
echo "Inserted user ID: " . $insert_id;


🔹 Output Example (users table)

id

name

email

created_at

1

John Doe

john@example.com

2025-08-18 20:00:00

2

Alice

alice@example.com

2025-08-18 20:05:00

3

Bob

bob@example.com

2025-08-18 20:05:00

4

Charlie

charlie@test.com

2025-08-18 20:06:00


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.