Codeigniter新闻教程视图方法不起作用


Codeigniter news tutorial view method not working

嘿,伙计们,我在学习codeigniter,我在新闻教程上。我差不多完成了,但我的查看方法是显示404,而不是新闻本身。我尝试使用以下代码进行调试

    echo '<pre>';
    var_dump($this->news_model->get_news($slug));
    exit();

然后返回

NULL

以下是我的控制器的工作原理,它调用方法

<?php 
class News extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('news_model');
    }
    public function index() {
        //echo '<pre>';
        //var_dump($this->news_model->get_news());
        //exit();
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';
        $this->load->view('templates/header',$data);
        $this->load->view('news/index',$data);
        $this->load->view('templates/footer');
    }
    public function view($slug) {
        //echo '<pre>';
        //var_dump($this->news_model->get_news($slug));
        //exit();
        $data['news'] = $this->news_model->get_news($slug);
        if (empty($data['news_item'])) {
            show_404();
        }
        $data['title'] = $data['news_item']['title'];
        $this->load->view('templates/header',$data);
        $this->load->view('news/view',$data);
        $this->load->view('templates/footer');
    }
}

我还是个初学者,所以我的调试解决方案是有限的。

$data['news'] = $this->news_model->get_news($slug);

应该是

$data['news_item'] = $this->news_model->get_news($slug);

根据代码的其余部分。

不要使用$slug,当你从set_news插入数据时,教程$slug设置为true,但我不明白为什么属性类型varchar slug可以保存布尔类型。这里是将变量$slug和all属性设置为db的代码。这里是管制员新闻的代码

public function set_news()
    {
        $this->load->helper('url');
        $slug = url_title($this->input->post('title'), 'dash', TRUE);
        $data = array(
            'title' => $this->input->post('title'),
            'slug' => $slug,
            'text' => $this->input->post('text')
        );
        return $this->db->insert('news', $data);
    }

将方法视图的代码编辑为

public function view($slug = NULL)
    {
            $data['news'] = $this->news_model->get_news();
            //echo print_r($data['news_item']['0']['title'], true);
            if (empty($data['news']))
            {
                    show_404();
            }
            $data['title'] = $data['news']['0']['title'];
            $this->load->view('templates/header', $data);
            $this->load->view('news/view', $data);
            $this->load->view('templates/footer');
    }

并将views/news/view.php编辑为

<?php foreach ($news as $news_item): ?>
    <h3><?php echo $news_item['title']; ?></h3>
    <div class="main">
            <?php echo $news_item['text']; ?>
    </div>
    <p><a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article</a></p><?php endforeach; ?>