如何减少mysql,codeigniter的数据加载时间

时间:2016-12-19 05:24:01

标签: php mysql codeigniter

我喜欢从这个方法中检索400多条记录,加载页面几乎需要2分钟。所以请帮我如何减少这种方法的加载时间。

function teacher_attendance_selector()

    {

        $data['year']       = $this->input->post('year');
        $data['timestamp']  =strtotime($this->input->post('timestamp'));
        $query = $this->db->get_where('teacher_attendance' ,array(
                  'teacher_id'=>$data['teacher_id'],
             'year'=>$data['year'],

        ));



        if($query->num_rows() < 1) {
            $teachers = $this->db->get_where('teacher' , array(

            ))->result_array();

            foreach($teachers as $row) {
                $attn_data['year']       = $data['year'];
                $attn_data['timestamp']  = $data['timestamp'];
                $attn_data['teacher_id'] = $row['teacher_id'];

                $this->db->insert('teacher_attendance' , $attn_data);  
            }

        }
  redirect(base_url().'index.php?admin/manage_teacher_attendance_view/'.$data['timestamp'],'refresh');
        }

1 个答案:

答案 0 :(得分:0)

您的插入查询花费了大量时间。 按照以下建议的方式,您可以将所有数据存储在一个数组中,然后您只能使用一个查询来插入存储在该数组中的所有记录。

请参阅下面的代码,您将获得有关如何实现性能的更多想法。

&#13;
&#13;
function teacher_attendance_selector()

    {

        $data['year']       = $this->input->post('year');
        $data['timestamp']  =strtotime($this->input->post('timestamp'));
        $query = $this->db->get_where('teacher_attendance' ,array(
                  'teacher_id'=>$data['teacher_id'],
             'year'=>$data['year'],

        ));



        if($query->num_rows() < 1) {
            $teachers = $this->db->get_where('teacher' , array())->result_array();

            $arr_batchinsert = array();

            foreach($teachers as $row) {
                $attn_data['year']       = $data['year'];
                $attn_data['timestamp']  = $data['timestamp'];
                $attn_data['teacher_id'] = $row['teacher_id'];
                
                // PREPARE ARRAY FOR BATCH INSERT
                $arr_batchinsert = $attn_data;
            }

            // insert here using insert_batch
            $this->db->insert_batch('teacher_attendance', $arr_batchinsert ); 


        }
  redirect(base_url().'index.php?admin/manage_teacher_attendance_view/'.$data['timestamp'],'refresh');
        }
&#13;
&#13;
&#13;