Mysql 为什么我的模板中有一个未定义的变量
我在控制器中执行以下操作。当我转到相应的视图时,我得到以下PHP错误Mysql 为什么我的模板中有一个未定义的变量,mysql,cakephp,pdo,Mysql,Cakephp,Pdo,我在控制器中执行以下操作。当我转到相应的视图时,我得到以下PHP错误 public function viewallpolice($id=NULL) { $customer = $this->Session->read('customer_id'); if ($customer>0) { $this->loadModel('Policy'); $results = $this->Policy->fin
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,第1行]
警告(2):为foreach()提供的参数无效[APP\View\User\viewallpolice.ctp,第1行]
客户姓名/手机号码:
注意(8):未定义变量:结果[APP\View\User\viewallpolice.ctp,第2行]
您的
foreach
循环不正确。有关更多信息,请参阅
由于您正在控制器代码中设置$results
,因此您需要如下内容:
<?php foreach ($results as $result): ?>
<p>Customer Name /Mobile : <?php echo $result['Policy']['customer_name']; ?></p>
<?php endforeach; ?>
客户姓名/手机号码:
我认为您使用的是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');
}
}
在模板中,如果“客户名称”字段位于表策略中:
<?php foreach ($results as $result): ?>
<p>Customer Name /Mobile : <?= $result['customer_name']; ?></p>
<?php endforeach; ?>
客户姓名/手机号码:
Notice(8):未定义变量:results[APP\View\User\viewallpolice.ctp,第1行]警告(2):为foreach()提供的参数无效[APP\View\User\viewallpolice.ctp,第1行]是否确实设置了results
?您还希望从策略->读取
函数调用中设置结果,还是从查找
函数中设置结果?老实说,你没有提供太多的信息。仅仅粘贴带有错误消息的代码并不是最好的方法。对于初学者,您可以在控制器内调试($customer)
,查看它的值(也就是说,它是否大于0
?)。在URL中,您是否传递了有效的策略$id
?你可以回答很多问题,但这应该是一个很好的起点。对不起,先生。事实上,我更新鲜,所以我不知道整个过程。我会再次检查..并请将您的问题命名为将来有用的东西。未定义变量:user
-控制器代码不尝试设置名为user的变量-不确定您为什么希望它工作..?如果我的ans为您工作,请单击接受选择权