dongweiben5229 2017-07-25 01:49
浏览 57
已采纳

PHP CODEIGNITER UPDATE问题

I can't update data in a record in CodeIgniter .

I have posted the code below:-

//CONTROLLER //RESERVATION.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Reservation extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('reservation_model','reservation');
    }

    public function index()
    {
        $this->load->helper('url');
        $this->load->view('manage_reservation');
    }
    public function reservationview()
    {
        $this->load->helper('url');
        $this->load->view('view_reservation');
    }

    public function ajax_list()
    {
        $list = $this->reservation->get_datatables();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $reservation) {
            $no++;
            $row = array();
            $row[] = $reservation->id;
            $row[] = $reservation->dateReserved;
            $row[] = $reservation->requestedBy;
            $row[] = $reservation->facility;
            $row[] = $reservation->dateFrom;
            $row[] = $reservation->dateTo;
            $row[] = $reservation->timeStart;
            $row[] = $reservation->timeEnd;
            $row[] = $reservation->status;
            $row[] = $reservation->items;
            $row[] = $reservation->purpose;

            //add html for action
            $row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
                  <a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';

            $data[] = $row;
        }

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->reservation->count_all(),
                        "recordsFiltered" => $this->reservation->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }

    public function ajax_edit($id)
    {

        $data = $this->reservation->get_by_id($id);

        $data->dateFrom = ($data->dateFrom == '0000-00-00') ? '' : $data->dateFrom;
        $data->dateTo = ($data->dateTo == '0000-00-00') ? '' : $data->dateTo;       // if 0000-00-00 set tu empty for datepicker compatibility
        echo json_encode($data);

    }

    public function ajax_add()
    {
        $this->_validate();
        $data = array(
                'id' => $this->input->post('id'),
                'dateReserved' => $this->input->post('dateReserved'),
                'requestedBy' => $this->input->post('requestedBy'),
                'facility' => $this->input->post('facility'),
                'dateFrom' => $this->input->post('dateFrom'),
                'dateTo' => $this->input->post('dateTo'),
                'timeStart' => $this->input->post('timeStart'),
                'timeEnd' => $this->input->post('timeEnd'),
                'status' => $this->input->post('status'),
                'items' => $this->input->post('items'),
                'purpose' => $this->input->post('purpose'),

            );
        $insert = $this->reservation->save($data);
        echo json_encode(array("status" => TRUE));
    }

    public function ajax_update()
    {
        $this->_validate();
        $data = array(

                'id' => $this->input->post('id'),
                'dateReserved' => $this->input->post('dateReserved'),
                'requestedBy' => $this->input->post('requestedBy'),
                'facility' => $this->input->post('facility'),
                'dateFrom' => $this->input->post('dateFrom'),
                'dateTo' => $this->input->post('dateTo'),
                'timeStart' => $this->input->post('timeStart'),
                'timeEnd' => $this->input->post('timeEnd'),
                'status' => $this->input->post('status'),
                'items' => $this->input->post('items'),
                'purpose' => $this->input->post('purpose'),



            );
        $this->reservation->update(array('id' => $this->input->post('id')), $data);
        echo json_encode(array("status" => TRUE));
    }

    public function ajax_delete($id)
    {
        $this->reservation->delete_by_id($id);
        echo json_encode(array("status" => TRUE));
    }


    private function _validate()
    {
        $data = array();
        $data['error_string'] = array();
        $data['inputerror'] = array();
        $data['status'] = TRUE;

        if($this->input->post('requestedBy') == '')
        {
            $data['inputerror'][] = 'requestedBy';
            $data['error_string'][] = 'Requested Name is required*';
            $data['status'] = FALSE;
        }

        if($this->input->post('dateFrom') == '')
        {
            $data['inputerror'][] = 'dateFrom';
            $data['error_string'][] = 'Please Select a Date*';
            $data['status'] = FALSE;
        }

        if($this->input->post('dateTo') == '')
        {
            $data['inputerror'][] = 'dateTo';
            $data['error_string'][] = 'Please Select a Date*';
            $data['status'] = FALSE;
        }

        if($this->input->post('timeStart') == '')
        {
            $data['inputerror'][] = 'timeStart';
            $data['error_string'][] = 'Please select a Time*';
            $data['status'] = FALSE;
        }

        if($this->input->post('timeEnd') == '')
        {
            $data['inputerror'][] = 'timeEnd';
            $data['error_string'][] = 'Please select a Time*';
            $data['status'] = FALSE;
        }

        if($this->input->post('status') == '')
        {
            $data['inputerror'][] = 'status';
            $data['error_string'][] = 'Please Indicate Status*';
            $data['status'] = FALSE;
        }

        if($this->input->post('items') == '')
        {
            $data['inputerror'][] = 'items';
            $data['error_string'][] = 'Please select an Item*';
            $data['status'] = FALSE;
        }

        if($this->input->post('purpose') == '')
        {
            $data['inputerror'][] = 'purpose';
            $data['error_string'][] = 'Please indicate a Purpose*';
            $data['status'] = FALSE;
        }

        if($data['status'] === FALSE)
        {
            echo json_encode($data);
            exit();
        }
    }

}

//MODEL //Reservation_model.php

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Reservation_model extends CI_Model {

        var $table = 'tblreservation';
        var $column_order = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose',null); //set column field database for datatable orderable
        var $column_search = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose'); //set column field database for datatable searchable just firstname , lastname , address are searchable

        var $order = array('id' => 'desc'); // default order 

        public function __construct()
        {
            parent::__construct();
            $this->load->database();
        }

        private function _get_datatables_query()
        {

            $this->db->from($this->table);

            $i = 0;

            foreach ($this->column_search as $item) // loop column 
            {
                if($_POST['search']['value']) // if datatable send POST for search
                {

                    if($i===0) // first loop
                    {
                        $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                        $this->db->like($item, $_POST['search']['value']);
                    }
                    else
                    {
                        $this->db->or_like($item, $_POST['search']['value']);
                    }

                    if(count($this->column_search) - 1 == $i) //last loop
                        $this->db->group_end(); //close bracket
                }
                $i++;
            }

            if(isset($_POST['order'])) // here order processing
            {
                $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
            } 
            else if(isset($this->order))
            {
                $order = $this->order;
                $this->db->order_by(key($order), $order[key($order)]);
            }
        }

        function get_datatables()
        {
            $this->_get_datatables_query();
            if($_POST['length'] != -1)
            $this->db->limit($_POST['length'], $_POST['start']);
            $query = $this->db->get();
            return $query->result();
        }

        function count_filtered()
        {
            $this->_get_datatables_query();
            $query = $this->db->get();
            return $query->num_rows();
        }

        public function count_all()
        {
            $this->db->from($this->table);
            return $this->db->count_all_results();
        }

        public function get_by_id($id)
        {
            $this->db->from($this->table);
            $this->db->where('id',$id);
            $query = $this->db->get();

            return $query->row();
        }

        public function save($data)
        {
            $this->db->insert($this->table, $data);
            return $this->db->insert_id();
        }

        public function update($where, $data)
        {
            $this->db->update($this->table, $data, $where);
            return $this->db->affected_rows();
        }

        public function delete_by_id($id)
        {
            $this->db->where('id', $id);
            $this->db->delete($this->table);
        }


}

VIEW = manage_reservation.php = save function

function save()
{
    $('#btnSave').text('saving...'); //change button text
    $('#btnSave').attr('disabled',true); //set button disable 
    var url;

    if(save_method == 'add') {
        url = "<?php echo site_url('reservation/ajax_add')?>";
    } else {
        url = "<?php echo site_url('reservation/ajax_update')?>";
    }

    // ajax adding data to database
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {

            if(data.status) //if success close modal and reload ajax table
            {
                $('#modal_form').modal('hide');
                reload_table();
            }
            else
            {
                for (var i = 0; i < data.inputerror.length; i++) 
                {
                    $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                    $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
                }
            }
            $('#btnSave').text('save'); //change button text
            $('#btnSave').attr('disabled',false); //set button enable 


        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
            $('#btnSave').text('save'); //change button text
            $('#btnSave').attr('disabled',false); //set button enable 

        }
    });
}

NEWBIE TO CODE IGNITER any help will be appreciated :)

  • 写回答

3条回答 默认 最新

  • dongxi5423 2017-07-25 02:00
    关注

    try

    public function update($where, $data){
       $this->db->where($where);
       $this->db->set($data); //array of new data
       $this->db->update($this->table);
       return $this->db->affected_rows();
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VMware安装虚拟网络驱动程序不成功,如何解决?(操作系统-linux)
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件