douyan1896 2019-01-22 07:04
浏览 48

CodeIgniter中的URI路由导致404错误

Second EDIT - Found the Problem, and answered it as well. First Edit - added my Post_model.php file as well for clearer explanation of my code. I am trying to redirect a Blogs slug to a separate page where I can show the entire blogs content.

here's an example slug

http://localhost/aag/posts/test-one 

Here's the Posts controller

<?php   
class Posts extends CI_Controller {
    public function index(){
         // Shows a blog listing

    }

    public function view($slug = NULL){
        $data['post'] = $this->post_model->get_posts($slug);
        if(empty($data['post'])){
            show_404();
        }
        $data['title'] = $data['post']['title'];

        $this->load->view('templates/header');
        $this->load->view('posts/view', $data);
        $this->load->view('templates/footer');

    }
}

The posts/view.php file

<h2><?php echo $post['title']; ?></h2>
<small class="post-date">Created on <?php echo $post['created_at']?></small><br>
<div class="post-body">
    <?php echo $post['body']; ?>
</div>

the Post_model.php

class Post_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
    }

    public function get_posts($slug = FALSE)
    {
        if ($slug === FALSE) {
            $query = $this->db->get('posts');
            return $query->result_array();
        }
        $query = $this->db->get_where('posts', array('slug' => '$slug'));
        return $query->row_array();
    }
}

routes.php

$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['(:any)'] = 'pages/view/$1';
  • 写回答

1条回答 默认 最新

  • drxm72811 2019-01-22 07:16
    关注

    Okay, so years of writing mysqli queries made me do this mistake. In my Post_model.php I am getting the data where (DB column field) slug should match the $slug that gets passed in, but I surrounded the slugs inside single quotes that was causing the error. Here's the working code now.

    class Post_model extends CI_Model
    {
        public function __construct()
        {
            $this->load->database();
        }
    
        public function get_posts($slug = NULL)
        {
            if ($slug === NULL) {
                $query = $this->db->get('posts');
                return $query->result_array();
            }
            $query = $this->db->get_where('posts', array('slug' => $slug));
            return $query->row_array();
        }
    }
    

    TLDR: Don't encapsulate your passed in arguments inside quotes.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度