CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
After creating a database and table, the next step is to insert data.
In CodeIgniter, you can insert records using:
Make sure database is loaded. Add this in autoload.php
:
$autoload['libraries'] = array('database');
Or load it manually:
$this->load->database();
users
tableclass 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
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."; } }
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!"; }
$this->db->insert('users', $data); $insert_id = $this->db->insert_id(); echo "Inserted user ID: " . $insert_id;
id |
name |
|
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 |