You can find Database Query for CRUD operation in CodeIgniter 4 below.
- SELECT query in CodeIgniter 4
- INSERT query in CodeIgniter 4
- UPDATE query in CodeIgniter 4
- DELETE query in CodeIgniter 4
SELECT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $table ="tableName"; $$email = "info@codypaste.com"; $status = "1"; $condition = "status =" . "'" . $status ."' AND email = '".$email."'"; $result = $this->db->table($table) ->select('*') ->where($condition); $record = $result->get()->getResult(); $numRows = count($record); $numRows = $result->get()->getNumRows(); print_r($record); echo $numRows; |
For Number of rows you can use ‘$result->get()->getNumRows();‘ butit will return 1 record more because of ‘$result->get()->getResult();‘
You can use only one of them ‘$result->get()->getNumRows();‘ OR ‘$result->get()->getResult();‘ for better result.
So, it’s preferred to use ‘count($record);‘ for number of rows.
INSERT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | $first_name = $this->request->getPost('first_name'); $last_name = $this->request->getPost('last_name'); $email = $this->request->getPost('email'); $table = "users"; $data = [ 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, 'phone' => $phone, 'pwd' => $pwd, 'otp' => $otp, 'status' => '0' ]; $result = $this->db ->table($table) ->insert($data); $affected_rows = $this->db->affectedRows(); if($affected_rows > 0){ return 1; }else{ return 0; } |
UPDATE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $table = "users"; $data = [ 'status' => 1 ]; $condition = "email = '".$email."'"; $result = $this->db ->table($table) ->where($condition) ->set($data) ->update(); $affected_rows = $this->db->affectedRows(); if($affected_rows > 0){ return 1; }else{ return 0; } |
DELETE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $table ="users"; $id = "1"; $condition = "id = '".$id."'"; $result = $this->db ->table($table) ->where($condition) ->delete(); $affected_rows = $this->db->affectedRows(); if($affected_rows > 0){ return 1; }else{ return 0; } |