1

I am new to PHP an YII framework don't be strict. I have some code that gets from google currency exchenge rate.

for ($i = 1; $i <= 3; $i++)
     {
         $model = WidgetCurrencyElement::model()->findByPk($i);

         $buy = 100.25*$er[$i];
         $buy = (int)$buy;
         $buy /= 100;

         $sale = $er[$i]/0.010025;
         $sale = (int)$sale;
         $sale /= 100;

         $model->buy = $buy;
         $model->sale = $sale;

         if(!$model->save()){
             print_r($model->getErrors());
             die("not saved!");
         }
     }
     $this->render('currency', array('er1' => $er[1], 'er2'=>$er[2], 'er3'=>$er[3]));
}

and it shows me

"PHP warning Creating default object from empty value". I can't understand why. What is the reason of this kind of error? The '$model' is not tottaly empty.

3
  • findByPk($i) is looping through for so do you all ids(1,2,3) available in database Commented Apr 29, 2015 at 9:57
  • 1
    reason should be that one or more of the ids not in db. Instead of finding items in a loop like this, it would be better to run one query and then loop through the results to bypass issues like this. Commented Apr 29, 2015 at 10:33
  • @YatinMistry you were right, the third id was missing, so I did as arkoad pointed me in his answer. Commented Apr 29, 2015 at 12:13

1 Answer 1

2

As Arkoak said, probably one or more id is not exist in database. So it's better to make sure object existence after finding it, then try to assign value to it:

for ($i = 1; $i <= 3; $i++)
 {
     $model = WidgetCurrencyElement::model()->findByPk($i);
     if($model != null)
     {
         $buy = 100.25*$er[$i];
         $buy = (int)$buy;
         $buy /= 100;

         $sale = $er[$i]/0.010025;
         $sale = (int)$sale;
         $sale /= 100;

         $model->buy = $buy;
         $model->sale = $sale;

         if(!$model->save()){
             print_r($model->getErrors());
             die("not saved!");
         }
     }

 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's a lot! Your answer helped me. I spend two hours for fixing that warning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.