Codeigniter: разбивка на страницы Пытается получить свойство необъектной ошибки

#php #codeigniter #pagination

#php #codeigniter #разбивка на страницы

Вопрос:

При разбивке на страницы я получаю ошибку при попытке перейти на любые страницы, кроме первой страницы (смещение = 0) вот мой код

URI: http://localhost/the-site/admin/hr/career_new/

URI со смещением: http://localhost/the-site/admin/hr/career_new/employee_id/desc/3

Ошибка 1

 A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: .../career_model.php
Line Number: 127
  

Ошибка 2

 A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: .../career_model.php
Line Number: 127
  

Строка ошибки, которую я прокомментировал This is the error line #127 в приведенном ниже коде модели. Это прямо перед return $ret

Модель

 public function sort($limit, $offset, $sort_by, $sort_order)
{

    $type          = $this->input->post('type');
    $emp_id        = $this->input->post('employee_id');
    $old_operation = $this->input->post('old_operation');
    $old_position  = $this->input->post('old_position');
    $new_operation = $this->input->post('new_operation');
    $new_position  = $this->input->post('new_position');
    $created       = $this->input->post('record_date');
    $effect        = $this->input->post('effective_date');

    $sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';

    $sort_columns = array(
        'type',
        'employee_id',
        'old_operation',
        'old_position',
        'new_operation',
        'new_position',
        'record_date',
        'effective_date',
        'reason',
    );

    $sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'id';

    // results query
    $q = $this->db
            ->select('*')
            ->from('career_path')
            ->like('type', $type)
            ->like('employee_id', $emp_id)
            ->like('old_operation', $old_operation)
            ->like('old_position', $old_position)
            ->like('new_operation', $new_operation)
            ->like('new_position', $new_position)
            ->like('record_date', $created)
            ->like('effective_date', $effect)
            ->limit($limit, $offset)
            ->order_by($sort_by, $sort_order);

    $ret['rows'] = $q->get()->result();

    // count query
    $q = $this->db
            ->select('COUNT(*) as count', FALSE)
            ->from('career_path')
            ->like('type', $type)
            ->like('employee_id', $emp_id)
            ->like('old_operation', $old_operation)
            ->like('old_position', $old_position)
            ->like('new_operation', $new_operation)
            ->like('new_position', $new_position)
            ->like('record_date', $created)
            ->like('effective_date', $effect)
            ->limit($limit, $offset)
            ->order_by($sort_by, $sort_order);

    $temp = $q->get()->result();
    $ret['num_rows'] = $temp[0]->count; // This is the error line #127

    return $ret;
}
  

Контроллер

 public function career_new($sort_by = 'employee_id', $sort_order = 'desc', $offset = 0)
{
    $this->data['title'] = '<i class="fa fa-briefcase"></i> ' . lang('crr_add');

    /*         * ***********************************************************
     * load loop with pagination
     * ****************************************************************** */

    $limit = get_option('per_page');

    // fields
    $this->data['columns'] = array(
        'id'             => 'ID',
        'type'           => 'Type',
        'employee_id'    => 'Employee ID',
        'old_operation'  => 'Old Operation',
        'old_position'   => 'Old Position',
        'new_operation'  => 'New Operation',
        'new_position'   => 'New Position',
        'record_date'    => 'Created',
        'effective_date' => 'Effected',
    );

    $results                   = $this->career_model->sort($limit, $offset, $sort_by, $sort_order);
    $this->data['careers']     = $results['rows'];
    $this->data['num_results'] = $results['num_rows'];

    $base_url   = base_url() . 'admin/hr/career_new/' . $sort_by . '/' . $sort_order;
    //$numbs      = $this->employees_model->filter_count();
    $total_rows = $this->data['num_results'];

    get_pagination($base_url, $total_rows, $limit, 6, 2, TRUE);

    //$this->pagination->initialize($config);
    $this->data['pagination'] = $this->pagination->create_links();

    $this->data['sort_by']    = $sort_by;
    $this->data['sort_order'] = $sort_order;

    /*         * ***********************************************************
     *  End: load loop with pagination
     * ****************************************************************** */

    $this->data['career'] = $this->career_model->get_new();

    $rules = $this->career_model->rules;
    $this->form_validation->set_rules($rules);

    if ($this->form_validation->run() == TRUE) {

        //db fields/columns to insert value
        $crr_fields = array(
            'type',
            'employee_id',
            'old_operation',
            'old_position',
            'new_operation',
            'new_position',
            'record_date',
            'effective_date',
            'reason',
        );

        $data = $this->career_model->array_from_post($crr_fields);

        if (empty($data['reason'])) {
            $data['reason'] = NULL;
        }

        $this->career_model->save($data);

        $data['old_position']  = get_employee_id_field($data['employee_id'], 'position');
        $data['old_operation'] = get_employee_id_field($data['employee_id'], 'operation');

        /* ----------------------------------------------------------------
         * Sending email once form validation runs true
          --------------------------------------------------------------- */
        $email_hr       = $this->config->item('hr_email_templates');
        $email_template = $this->config->item('crr_new_email');
        $message = $this->load->view($email_hr . $email_template, $data, true);

        $this->email->clear();
        $this->email->from('atlassystem@apolloblake.com', get_config_option('site_name'));
        $this->email->to(get_user_data('email', 1));
        $this->email->subject(get_config_option('site_name') . ' - ' . $this->lang->line('crr_new_subject'));
        $this->email->message($message);

        if ($this->email->send()) {
            // set session notification message
            $this->session->set_flashdata('message', sprintf(lang('crr_record_added'), '#' . $data['employee_id']));
            $this->data['message']      = $this->session->flashdata('message');
            $this->session->set_flashdata('message_type', 'success');
            $this->data['message_type'] = $this->session->flashdata('message_type');

            redirect(current_url(), 'refresh');
        } else {
            $this->load->view('hr/career/form', $this->data);
        }
    }

    $this->load->view('hr/career/form', $this->data);
}
  

View

 <div class="panel-body"> 

    <?php
    if (validation_errors()):
        echo show_alert(validation_errors(), TRUE, 'danger', 'glyphicon glyphicon-warning-sign');
    endif;
    ?>

    <div class="table-responsive">                    
        <table cellpadding = "0" cellspacing = "0" border = "0" class = "table table-hover table-bordered datatables center" id = "">
            <thead>
                <tr class = "active center">

                    <?php foreach ($columns as $field_name => $field_display): ?>

                        <th <?= ($sort_by == $field_name ) ? "class="sort_$sort_order"" : NULL ?>>
                            <?= anchor("admin/hr/career_new/$field_name/" . (($sort_order == 'asc' amp;amp; $sort_by == $field_name) ? 'desc' : 'asc'), $field_display); ?>
                            <?= (($sort_order == 'asc' amp;amp; $sort_by == $field_name) ? '<span class="glyphicon glyphicon-sort-by-attributes"></span>' : '<span class="glyphicon glyphicon-sort-by-attributes-alt"></span>'); ?>
                        </th>

                    <?php endforeach; ?>

                </tr>
            </thead>
            <tbody>
                <?php
                foreach ($careers as $crr):
                    echo '<tr>';
                    foreach ($columns as $field_name => $field_display):
                        echo '<td>', $crr->$field_name, '</td>';
                    endforeach;
                    echo '</tr>';
                endforeach;
                ?>
            </tbody>
        </table><!--end table-->
    </div> 
    <?php if (strlen($pagination)): ?>
        <div>
            <?= $pagination; ?>
        </div>
    <?php endif; ?>

</div>
  

вывод var_dump

использование var_dump($temp); в модели, которую я получаю ниже $offset=0 , означает первую страницу

 array (size=1)
  0 => 
    object(stdClass)[37]
      public 'count' => string '7' (length=1)
  

и var_dump($ret['num_rows']);

 tring '7' (length=1)
  

На второй странице с offset=3 получением ошибки с var_dump выводом ниже

 var_dump($temp);

array (size=0)
  empty
  

и

 var_dump($ret['num_rows']);

null
  

Комментарии:

1. Что, если вы измените «$ temp = $ q-> get()-> result();» на «$ temp = $ q-> get()-> result_array();»

2. @Craig хм .. дай я попробую..

3. Упс.. Это все испортило, так как теперь это результирующий массив. Так что мое мнение также пострадало. Так что я думаю, что должно быть какое-то другое решение для этого

4. Я обновляю вопрос с помощью var_dump()

5. @karanthakkar все еще ошибка. Разница только в том, что вместо двух ошибок я получаю только одну (я имею в виду то же сообщение об ошибке)

Ответ №1:

Итак, я исправил проблему. Это была небольшая и простая задача, но мне потребовалось 4-5 часов, чтобы найти и исправить ее.

Я просто скопировал и вставил запрос результата и подсчета в модель, и там я допустил ошибку. Я просто пропустил последние два ->limit() и ->order_by() функцию, которая не требовалась для подсчета общего количества строк. Это создавало проблему. При использовании разбивки на страницы учитывалось ограничение и смещение. Итак, окончательный исправленный код выглядит следующим образом

Модель

 public function sort($limit, $offset, $sort_by, $sort_order)
{

    $type          = $this->input->post('type');
    $emp_id        = $this->input->post('employee_id');
    $old_operation = $this->input->post('old_operation');
    $old_position  = $this->input->post('old_position');
    $new_operation = $this->input->post('new_operation');
    $new_position  = $this->input->post('new_position');
    $created       = $this->input->post('record_date');
    $effect        = $this->input->post('effective_date');

    $sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';

    $sort_columns = array(
        'type',
        'employee_id',
        'old_operation',
        'old_position',
        'new_operation',
        'new_position',
        'record_date',
        'effective_date',
        'reason',
    );

    $sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'id';

    // results query
    $q = $this->db
            ->select('*')
            ->from('career_path')
            ->like('type', $type)
            ->like('employee_id', $emp_id)
            ->like('old_operation', $old_operation)
            ->like('old_position', $old_position)
            ->like('new_operation', $new_operation)
            ->like('new_position', $new_position)
            ->like('record_date', $created)
            ->like('effective_date', $effect)
            ->limit($limit, $offset)
            ->order_by($sort_by, $sort_order);

    $ret['rows'] = $q->get()->result();

    // count query
    $q = $this->db
            ->select('COUNT(*) as count', FALSE)
            ->from('career_path')
            ->like('type', $type)
            ->like('employee_id', $emp_id)
            ->like('old_operation', $old_operation)
            ->like('old_position', $old_position)
            ->like('new_operation', $new_operation)
            ->like('new_position', $new_position)
            ->like('record_date', $created)
            ->like('effective_date', $effect); // removed limit and order_by

    $temp = $q->get()->result();
    $ret['num_rows'] = $temp[0]->count; // This is the error line #127

    return $ret;
}