在codeiginter中创建自定义URL

时间:2016-03-01 13:33:23

标签: php codeigniter url-rewriting custom-url

我希望在网址中显示我的产品名称 现在我得到我的产品id和我的网址显示这样。 www.mydomain.com/home/single/1

我想用产品名称显示我的产品网址。 www.mydomain.com/home/single/New-Dell-Laptop

这是我的代码,它带有它的id号。

控制器

//get all products
public function index()
    {
        $data['products'] = $this->front->get_products();
        $this->load->view('index',$data);
    }

    //get single product
public function single($id)
    {
        $data['product']=$this->front->get_product($id);
        $this->load->view('product',$data);
    }

模型

//get all products
    public function get_products()
    {
        $this->db->select()
                 ->from('vendor_products')
                 ->where('DESC','date_added');
        $data = $this->db->get();
        return $data->result_array();
    }

        //get single product
    public function get_product($id)
    {
        $this->db->select()
                 ->from('vendor_products')
                 ->where('prod_id',$id);
        $data = $this->db->get();
        return $data->first_row('array');
    }

视图

//显示所有产品index.php

<?php foreach($products as $one) : ?>
            //create link for single product
        <a href="<?=base_url();?>home/single/<?=$one['prod_id'];?>">

            <?=$one['product_name'];?>
        </a>
        <p><?=$one['product_price'];?></p>

//显示单品(product.php)

<p><?=$product['product_name'];?></p>
        <p><?=$product['product_price'];?></p>
        <p><?=$product['product_description'];?></p>

2 个答案:

答案 0 :(得分:1)

你要人性化的字符串会在一个字段中,对吧?

www.mydomain.com/home/single/New-Dell-Laptop

因此,如果您在数据库中选择“新戴尔笔记本电脑”

它将返回1条记录,对吗?如果是这样,您可以在配置中的路由上配置类似的内容。

$route['single/{product}'] = 'productController/{product}';

然后当你加载productController / New-Dell-Laptop

您可以使用$ this-&gt; uri-&gt; segment(3)来获取值,并在数据库中搜索,检索页面并向用户显示。

你应该使用这样的东西:

www.mydomain.com/home/single/34/New-Dell-Laptop

其中34将是该页面的ID,并且您将很容易找到数据库,但如果您搜索“新戴尔笔记本电脑”,您不应该遇到麻烦

答案 1 :(得分:0)

您可以使用路线。

config/routes.php

require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->get('vendor_products');
$result = $query->result();
foreach( $result as $row )
{
    $route["home/single/" . $row->product_name] = "home/single/" . $row->prod_id;
} 

然后在您看来,改变

<a href="<?=base_url();?>home/single/<?=$one['prod_id'];?>">`

通过

<a href="<?=base_url();?>home/single/<?=$one['product_name'];?>">`
相关问题