CRUD Using Codeigniter

5 Dec

CRUD Using Codeigniter

Db operations using codeigniter is explained briefly with codes.

Add a new row
A row can be inserted as shown below. To get the unique id of the row inserted, we have to use the function: $this->db->insert_id().

$data['user_gid'] = $user_gid;
$data['username'] = $user_name;
$data['email'] = $email;
$this->db->insert("mytable", $data);
$user_id = $this->db->insert_id();

Update a row
To update a row, we have to pass a where condition.
mutiple where conditions are possible. Below sample code just used one where condition.

$data['user_gid'] = $user_gid;
$data['username'] = $user_name;
$data['email'] = $email;
$this->db->where('user_id', $user_id);
$this->db->update('mytable', $data);

Select a row
To select a row that matches a where condition, we have to pass a
where condition just like we passed for update.
$this->db->select(“*”) will select all fields of the table.
To select just one field or specific fields we can specify the field names.

//get all fields
$this->db->select("*");
//to get  email and username
//$this->db->select("username,email");
$this->db->from("mytable");
$this->db->where('user_id', $user_id);
$query = $this->db->get();
$row = $query->row_array();
return $row;

Select all rows

$this->db->select("*");
$this->db->from("mytable");
$query = $this->db->get();
$rows = $query->result();
return $rows;

Delete a row

$where = array(
    'user_id' => $user_id
);
$this->db->delete("mytable", $where);

Leave a Reply

Your email address will not be published. Required fields are marked *