【问题标题】:Undefined database variable未定义的数据库变量
【发布时间】:2020-11-28 22:10:32
【问题描述】:

Blog.php代码如下:

    <?php namespace App\Controllers;
    
    use App\Models\BlogModel;
    
    class Blog extends BaseController
    {
        public function index()
        {
            $model = new BlogModel();
    
            //echo "<pre>";
    
            //print_r($model);
    
            $dados = [
                'posts' => $model->get()->paginate(5),
                'pager' => $model->pager
            ];
            return view('posts/blog_index', $dados);
        }

blog_index.php 代码如下:

    <?= $this->extend('layouts/main') ?>
    
    <?= $this->section('content') ?> 
 

    <?= $this->include('/components/busca_blog', $dados['posts'] ) ?>   
    <?= $this->include('/components/posts_recentes', $dados['posts'] ) ?>   
    <?= $this->include('/components/categorias', $categorias) ?>   
    <?= $this->include('/components/arquivo', $dados['posts'] ) ?>

我看不出我的错误在哪里,它引发了一个错误异常:“未定义的变量:dados”。关于 $categorias 变量,我正在学习如何为每个控制器使用多个表。

Codeigniter 版本:4.0.4 通过xampp运行

【问题讨论】:

  • $posts 而不是$dados['posts'] 等。不时仔细阅读手册。

标签: php codeigniter view controller codeigniter-4


【解决方案1】:

Controller Blog.php

class Blog extends BaseController
{
    public function index()
    {
        $model = new BlogModel();

        $dados = [
            'posts' => $model->get()->paginate(5),
            'pager' => $model->pager
        ];
        return view('posts/blog_index', $dados);
    }
}

查看 blog_index.php

<?= $this->include('/components/posts_recentes', $posts) ?> 

    if(!empty($posts))
    {
        print_r($posts);
    }

注意:-参考请看:-

https://codeigniter4.github.io/userguide/outgoing/views.html#adding-dynamic-data-to-the-view

【讨论】:

    【解决方案2】:

    更新您的 blog_index.php 页面: 来自

    <?= $this->include('/components/busca_blog', $dados['posts'] ) ?>
    <?= $this->include('/components/posts_recentes', $dados['posts'] ) ?>   
    <?= $this->include('/components/categorias', $categorias) ?>   
    <?= $this->include('/components/arquivo', $dados['posts'] ) ?>
    

    <?= $this->include('/components/busca_blog', $posts ) ?>   
    <?= $this->include('/components/posts_recentes', $posts ) ?>   
    <?= $this->include('/components/categorias', $categorias) ?>   
    <?= $this->include('/components/arquivo', $posts ) ?>
    

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多