The variable product_purchase
isn't initialized
If there is no results for the previous find call, the variable $product_purchase
will not be defined triggering an undefined variable error. This will be the case if there is no logged in user:
public function beforeRender(){
// will be null if there is no user
$id = $this->Auth->user('idUser');
// unnecessary find call if there is no user, returning no rows
$this->loadModel('Userinfo');
$data= $this->Userinfo->find('all',array(
'conditions' => array('Userinfo.User_id' => $id)
));
// will not enter this foreach loop as data is empty
foreach($data as $d){
$product_purchase = $d['Userinfo']['product_purchase'];
}
// $product_purchase is undefined.
$this->set('userinfo',$product_purchase);
}
For the code in the question, just initialize the variable earlier:
public function beforeRender(){
$product_purchase = null;
$producut_purchase may get overwritten
Note that if there is more than one row of data returned for this query:
foreach($data as $d){
$product_purchase = $d['Userinfo']['product_purchase'];
}
The $product_purchase
variable will only contain the value of the last row.
If there is only ever one result - use an appropriate method. Don't use find('all')
- use find('first')
. Or given the fact that only one field is being retrieved - directly use the field
method:
$product_purchase = $this->Userinfo->field(
'product_purchase',
array('Userinfo.User_id' => $id))
);