提问人:Fadjrin 提问时间:11/4/2023 最后编辑:OlivierFadjrin 更新时间:11/5/2023 访问量:70
Codeigniter 4 中未定义的变量$home
Undefined variable $home in Codeigniter 4
问:
我是 CodeIgniter 4 的新手,遇到了一个问题。尝试将数据从控制器传递到视图时,我收到错误消息 ErrorException: Undefined variable $home。
这是我正在使用的代码:
型号 ():App\Models\indexModel
namespace App\Models;
use CodeIgniter\Model;
class indexModel extends Model
{
protected $table = "home";
protected $allowedFields = [
'front_name',
'back_name',
'jalan',
'email',
'telepon',
'facebook',
'whatsapp',
'instagram'
];
}
控制器 ():App\Controllers\Index
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\indexModel;
class Index extends Controller
{
public function indexController()
{
//model initialize
$account = new indexModel();
$data = array(
'home' => $account->findAll()
);
echo view('partial/header', $data);
}
}
视图 ():partial/header
<div class="col-md-6 text-center text-lg-right">
<div class="d-inline-flex align-items-center">
<?php foreach ($home as $key => $account): ?>
<a class="text-white px-3" href="<?= $account['facebook'] ?>">
<i class="fab fa-facebook-f"></i>
</a>
<a class="text-white px-3" href="<?= $account['whatsapp'] ?>">
<i class="fab fa-whatsapp"></i>
</a>
<a class="text-white px-3" href="<?= $account['instagram'] ?>">
<i class="fab fa-instagram"></i>
</a>
<?php endforeach; ?>
</div>
</div>
我已经检查过了,似乎我的代码是正确的,但我仍然收到此错误。谁能帮我了解问题所在以及如何解决?谢谢!
答:
0赞
steven7mwesigwa
11/5/2023
#1
而不是:
'home' => $account->findAll()
用:
'home' => $account->findAll() ?? []
评论
1赞
Vickel
11/5/2023
注意:Null 合并运算符 ??
是作为 PhP 7 中的新功能引入的
0赞
steven7mwesigwa
11/5/2023
@Vickel 感谢您的提醒。我相信这一切都很好,因为 codeigniter4/CodeIgniter4 需要 PHP 7.4 或更高版本才能开始。所以这应该仍然有效。
1赞
Vickel
11/5/2023
只是想添加注释,因为有人可以尝试与 CI-3.x(可能在遗留或学习)项目中一起使用,与 PhP 5.x 一起使用??
评论
$account->findAll()
print_r($data);die;
<?php foreach ($home[0] as $key => $account): ?>
将为您提供第一个主阵列的结果。如果您只希望返回一个记录集,那很好,如果不是,则需要添加另一个外部 foreach 循环来捕获 home[0]、home[1] 等中的记录集......