phpcodeigniterundefined-variable

Message: Undefined variable: beauty_detail in CODEIGNITER


I have a form where user can select either book or beauty radio button. Code is working fine on book but showing an error on beauty. Code is the same except data fetch from database is different. I have tried but still stuck.

ERROR A PHP Error was encountered Severity: Notice Message: Undefined variable: beauty_detail Filename: controllers/Welcome.php Line Number: 87

        if($result == 0){
            echo "no recommendation";
        } else{

            foreach($result as $key=>$value){
                $q = $this->mymodel->fetchBeautydetail($key);
                foreach($q as $val){

                    $beauty_detail[$val->user_id]['product_id'] = $val->product_id; 
                    $beauty_detail[$val->user_id]['product_rating'] = $val->rating;
                }
            }
(line number: 87) $this->load->view('beauty_dashboard', ['beauty_detail'=>$beauty_detail]);
        }

Solution

  • Problem is scope.

    Try following. (Declaring beauty_detail out of foreach)

    $beauty_detail;
    foreach($result as $key=>$value){
                    $q = $this->mymodel->fetchBeautydetail($key);
                    foreach($q as $val){
    
                        $beauty_detail[$val->user_id]['product_id'] = $val->product_id; 
                        $beauty_detail[$val->user_id]['product_rating'] = $val->rating;
                    }
                }
    $this->load->view('beauty_dashboard', ['beauty_detail'=>$beauty_detail]);
            }