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

时间:2015-11-19 16:36:59

标签: php codeigniter mamp

嘿伙计们我正在学习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');

    }

}

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

2 个答案:

答案 0 :(得分:1)

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

应该是

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

根据你的其余代码。

答案 1 :(得分:0)

不要使用$ slug,当你从set_news插入数据时教程$ slug设置为true但我不明白为什么属性类型varchar slug可以保存boolean类型。这里是将变量$ slug和所有属性设置为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; ?>