codeigniter view, add, update and delete

前端 未结 2 1868
梦谈多话
梦谈多话 2021-02-10 06:23

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.

<
2条回答
  •  野的像风
    2021-02-10 07:00

    You can use this as an example

    class Crud extends Model {
        // selecting records by specifying the column field
        function select()
        {
            // use $this->db->select('*') if you want to select all the records
            $this->db->select('title, content, date');
            // use $this->db->where('id', 1) if you want to specify what row to be fetched
            $q = $this->db->get('mytable');
    
            // to get the result
            $data = array();
            // for me its better to check if there are records that are fetched
            if($q->num_rows() > 0) { 
                // by doing this it means you are returning array of records
                foreach($q->result_array() as $row) {
                    $data[] = $row;
                }
                // if your expecting only one record will be fetched from the table
                // use $row = $q->row();
                // then return $row;
            }
            return $data;
        }
    
        // to add record
        function add()
        {
            $data = array(
               'title' => 'My title' ,
               'name' => 'My Name' ,
               'date' => 'My date'
            );
    
            $this->db->insert('mytable', $data); 
        }
    
        // to update record
        function update()
        {
            $data = array(
               'title' => $title,
               'name' => $name,
               'date' => $date
            );
    
            $this->db->where('id', 1);
            $this->db->update('mytable', $data); 
        }
    
        // to delete a record
        function delete()
        {
            $this->db->where('id', 1);
            $this->db->delete('mytable');
        }
    }
    

    Some of this are from codeigniter userguide.

    To view the records,

    If return data is array of records,

       foreach($data as $row)
       {
           echo $row['title'] . "
    "; }

    If the return data is an object (by using $q->row),

       echo $data->title;
    

    This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.

提交回复
热议问题