Thursday, 30 August 2018

Foreach loop does not work in the codeigniter model and the controller at a time

My simple foreach loop is working damn weird, please help me to solve this

here are my codes of controller
public function index()
{
    $this->load->model('file_list');
    $query = 'SELECT * FROM `files_data` WHERE file_extension = "jpg" and size > 0 LIMIT 0,10';
    foreach($this->db->query($query)->result() as $file){
        $data['check'] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
    }

    //$this->load->view('viewtest', $data);

    //$this->home_footer();

}

and here is model
public function preview_maker($file_id, $file_full_path, $extension){
    if(file_exists('preview/'.$file_id.'.jpg')){
        $preview = 'preview/'.$file_id.'.jpg';
    } else {
        if($extension == 'jpg' || $extension == 'gif' || $extension == 'png'){
            $config = array(
            'source_image' => 'stuff'.$file_full_path, //get original image
            'new_image' => 'preview/'.$file_id.'.jpg', //save as new image //need to create thumbs first
            'maintain_ratio' => true,
            'width' => 80,
            'height' => 80
                    );

            $this->load->library('image_lib', $config); //load library
            $this->image_lib->resize(); //do whatever specified in config
            $preview = '/preview/'.$file_id.'.jpg';
        } elseif ($extension == 'mp3'){
            $preview = '/preview/music.jpg';
        } elseif ($extension == 'apk'){
            $preview = '/preview/android.jpg';
        } elseif ($extension == 'jar'){
            $preview = '/preview/java.png';
        } elseif ($extension == 'zip'){
            $preview = '/preview/zip.jpg';
        } elseif ($extension == '3gp' || $extension == 'mp4' || $extension == 'avi'){
            $preview = '/preview/movie.png';
        }
    }
    return $preview;
}

The problem is, foreach loop is not working continious, its working for 1 record only for each refresh, then next record next refresh

as @prix was trying to tell you,
foreach($this->db->query($query)->result() as $file){
    $data['check'] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}

should read
foreach($this->db->query($query)->result() as $file){
    $data['check'][] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}

otherwise you just keep writing over the top of your value.

0 comments:

Post a Comment