我在控制器中有以下操作。当我转到相应的View时,我收到以下PHP错误。
public function viewallpolice($id=NULL) {
$customer = $this->Session->read('customer_id');
if ($customer>0) {
$this->loadModel('Policy');
$results = $this->Policy->find(
'all',
array('conditions' => array('customer_id' => $customer))
);
$this->set('results', $this->Policy->read(null, $id));
} else {
$this->Session->setFlash('error');
}
}
查看所有警察代码:
<?php foreach ($user as $result) ?>
<p>Customer Name /Mobile : <?php echo $result['Policy']['customer_name']; ?></p>
错误:
注意(8):未定义的变量:user [APP \ View \ User \ viewallpolice.ctp,line 1]
警告(2):为foreach()[APP \ View \ User \ viewallpolice.ctp,第1行]提供的参数无效
客户名称/手机:
注意(8):未定义的变量:结果[APP \ View \ User \ viewallpolice.ctp,第2行]
答案 0 :(得分:1)
我认为你正在使用cakephp 3。 在您的控制器中:
public function viewallpolice($id=NULL) {
$customer = $this->Session->read('customer_id');
if ($customer>0) {
$this->loadModel('Policy');
$results = $this->Policy->find('all',['conditions' =>['customer_id' => $customer]] )->toArray();;
$this->set('results', $results);
//use pr($result) to print the result array
} else {
$this->Session->setFlash('error');
}
}
如果customer_name字段在表策略中,则在模板中:
<?php foreach ($results as $result): ?>
<p>Customer Name /Mobile : <?= $result['customer_name']; ?></p>
<?php endforeach; ?>
答案 1 :(得分:0)
您的foreach
循环不正确。有关详细信息,请参阅documentation for foreach
。
由于您在控制器代码中设置$results
,因此您需要以下内容:
<?php foreach ($results as $result): ?>
<p>Customer Name /Mobile : <?php echo $result['Policy']['customer_name']; ?></p>
<?php endforeach; ?>