codeigniter view, add, update and delete

marikudo picture marikudo · Aug 18, 2010 · Viewed 22.7k times · Source

I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.

Just a simple one like creating addressbook for newbie.

thanks,

best regards

Answer

vikmalhotra picture vikmalhotra · Aug 18, 2010

Some sample queries in Codeigniter

class Names extends Model {
  function addRecord($yourname) {
    $this->db->set("name", $yourname);
    $this->db->insert("names");
    return $this->db->_error_number(); // return the error occurred in last query
  }
  function updateRecord($yourname) {
    $this->db->set("name", $yourname);
    $this->db->update("names");
  }
  function deleteRecord($yourname) {
    $this->db->where("name", $yourname);
    $this->db->delete("names");
  }
  function selectRecord($yourname) {
    $this->db->select("name, name_id");
    $this->db->from("names");
    $this->db->where("name", $yourname);
    $query = $this->db->get();
    return $this->db->result();
  }
  function selectAll() {
     $this->db->select("name");
     $this->db->from("names");
     return $this->db->get();
  }
}

More information and more ways for CRUD in codeigniter active record documentation More about error number over here

A sample controller

class names_controller extends Controller {
   function addPerson() {
      $this->load->Model("Names");
      $name = $this->input->post("name"); // get the data from a form submit
      $name = $this->xss->clean();
      $error = $this->Names->addRecord($name);
      if(!$error) {
         $results = $this->Names->selectAll();
         $data['names'] = $results->result();
         $this->load->view("show_names", $data);
      } else {
         $this->load->view("error");
      }
   }
}

More about controllers over here

A sample view - show_names.php

<table>
  <tr>
    <td>Name</td>
  </tr>
  <?php foreach($names as $row): ?>
  <tr><td><?ph echo $row->name; ?></td></tr>
  <?php endforeach; ?>
</table>

More about codeigniter views over here