如何使用slug?
将举例说明:
URL - http://www.example.com/products/apple-iphone-5S-16GB-brand-new/
1) 假设您有一个产品页面,并且产品页面当然需要来自 URL 的一些数据来了解要显示的产品。
2) 在我们使用从 URL 获取的 id 查询数据库之前。但是现在我们将做同样的事情(查询我们的数据库),只需将 id 替换为 slug 就可以了!
3)因此在您的数据库中添加一个名为 slug 的附加列。下面将是您更新的产品数据库结构(只是一个示例)。
Columns Values
id (int(11), PK) 1
title (varchar(1000)) Apple iPhone 5S 16GB
slug (varchar(1000)) apple-iphone-5S-16GB-brand-new
price (varchar(15)) 48000
thumbnail (varchar(255)) apple-iphone-5S-16GB-brand-new.jpg
description (text) blah blah
...
...
我之前也回答过 slug。检查它是否有帮助。
How to remove params from url codeigniter
编辑:
为此,您必须进行以下更改 -
1) 创建以下 2 个表格
slug_table:
id (PK) | slug | category_id (FK)
category_table:
id (PK) | title | thumbnail | description
2) config/routes.php
$route['/(:any)'] = "category/index/$1";
3) models/category_model.php(创建新文件)
class Category_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->db = $this->load->database('default',true);
}
public function get_slug($slug)
{
$query = $this->db->get_where('slug_table', array('slug' => $slug));
if($query->num_rows() > 0)
return $query->row();
return false;
}
public function get_category($id)
{
$query = $this->db->get_where('category_table', array('id' => $id));
if($query->num_rows() > 0)
return $query->row();
return false;
}
}
4) controllers/category.php(创建新文件)
class Category extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('category_model');
}
public function index($slug)
{
$sl = $this->category_model->get_slug($slug);
if($sl)
{
$data['category'] = $this->category_model->get_category($sl->category_id);
$this->load->view('category_detail', $data);
}
else
{
// 404 Page Not Found
}
}
}
5) views/category_detail.php(创建新文件)
<label>Category title: <?php echo $category->title; ?></label><br>
</label>Category description: <?php echo $category->description; ?></label>