[英]URI routing in CodeIgniter causes 404 error
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.
第一次编辑-也添加了我的Post_model.php文件,以便更清晰地解释我的代码。 I am trying to redirect a Blogs slug to a separate page where I can show the entire blogs content.
我正在尝试将Blog条目重定向到一个单独的页面,在其中可以显示整个Blog的内容。
here's an example slug 这是一个例子
http://localhost/aag/posts/test-one
Here's the Posts controller 这是Posts控制器
<?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 posts/view.php
文件
<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
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';
Okay, so years of writing mysqli
queries made me do this mistake. 好吧,这么多年编写
mysqli
查询使我犯了这个错误。 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. 在我的
Post_model.php
我得到的数据(数据库列字段)段slug
应该与传入的$slug
相匹配,但是我将段$slug
包围在引起错误的单引号内。 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. TLDR:不要将传入的参数封装在引号内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.