douya2007 2013-05-21 15:17
浏览 40
已采纳

消息未定义变量:视图页面上的新闻

I'm new to PHP and CodeIgniter, and saw that there is many questions mentioning this and been trying them all but nothing seems to work. Everything is auto-loaded in configuration, the database is running and function for posting to database are working but writing to view page doesn't work at all. Except for displaying username, but for that I create a new variable on view page.

Controller

 public function ShowNews()
 {
     $data = array();
     $this->load->model('user');
     $data['news'] = $this->user->getNews();
     $this->load->vars($data);
}

Model

function getNews(){
    $q = $this->db->get('News');
    if($q->num_rows() > 0){
        return $q->result();
    }
    return FALSE;
}

View

<?php foreach($news as $row) : ?>

<li><?php echo $row->Title;  ?> </li>
<li><?php echo $row->Date; ?></li>      

<?php endforeach; ?>

This is the error EDIT ves to news

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: news

Filename: admin/Pocetna.php

Line Number: 64
A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: admin/Pocetna.php

Line Number: 64

Using WAMP, NetBeans with CodeIgniter. I saw it has to be something with passing data from controller to view but I can't figure it out and been trying few days already, but always having problems.

  • 写回答

1条回答 默认 最新

  • dongyan1936 2013-05-21 15:25
    关注

    You're not passing $data to your view. Your controller should be like this:

    public function show_news()
    {
        $this->load->model('user');
    
        $data = [];
        $data['news'] = $this->user->get_news();
    
        $this->load->view('news', $data);
    }
    

    Your view should also be checking if $news is FALSE, because you'll have some issues with foreach if you loop over the value FALSE. Your model should also be returning result_array not result, foreach cam't loop over objects..

    public function get_news()
    {
        $q = $this->db->get('News');
    
        return($q->num_rows() > 0) ? $q->result_array() : FALSE;
    }
    

    Your view should look something like this:

    <?php
        if($news !== FALSE)
        {
            foreach($news as $row)
            {
                echo "<li>{$row['title']}</li>";
                echo "<li>{$row['date']}</li>"; 
            }
        }
        else
        {
            echo "No news to see here!";
        }
    ?>
    

    Your title also doesn't link up with the error in the post, so that's the solution to the one in the title.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作