从数据库动态获取产品标题并放入URL codeigniter

时间:2015-12-02 14:54:26

标签: php .htaccess codeigniter url-rewriting

我在代码点火器框架中工作。我想通过在stackoverflow中传递ID来动态地从数据库获取产品标题。正如我们在SO中看到的那样,当我删除标题并点击输入然后在URL中自动生成标题。这是怎么回事谷歌搜索后我发现它可以通过使用.htaccess完成,但我无法得到它如何实现它。

我的.htaccess是:

 RewriteEngine on 
 RewriteCond $1 !^(index.php|resources|robots.txt) 
 RewriteCond %{REQUEST_FILENAME} !-f 
 RewriteCond %{REQUEST_FILENAME} !-d 
 RewriteRule ^(.*)$ index.php/$1 [L,QSA]

任何示例和教程都会有所帮助。谢谢你。

1 个答案:

答案 0 :(得分:1)

使用htaccess文件无法完成您要做的事情,因为它涉及的更多一些。据说这不是真的很难。以下将转换网址,例如:

http://example.com/store/product/33

http://example.com/store/product/33/some-product-title


数据库:

enter image description here

控制器:

class store extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper("url");
        $this->load->model('store_model','store');

    }

    function product($id, $slug=''){

        //if no slug value passed then we obtain the product title and redirect
        if($slug === ''){

            //get the title value from products table and run it through _slugify function
            $slug = $this->_slugify($this->store->read_productTitle($id));

            redirect('store/product/'. $id . '/' . $slug);

        }

        //The rest of your logic will go here, then you will load your view. For the purpose
        //of examples I'm just going to echo a string.
        echo "This is a string";

    }

    function _slugify($text){ 

        //YOU CAN CHANGE THIS FUNCTION TO FORMAT THE TITLE VALUE HOWEVER
        //YOU WANT IT TO APPEAR IF THIS DOESN'T WORK FOR YOU. ALSO, THIS FUNCTION
        //WOULD MAKE MORE SENSE IN A HELPER FILE.

        // replace non letter or digits by -
        $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

        // trim
        $text = trim($text, '-');

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // lowercase
        $text = strtolower($text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        if (empty($text))
        {
          return 'n-a';
        }

        return $text;
    }

}

型号:

class store_model extends CI_Model {

    function __construct() {
        parent::__construct();

    }

    function read_productTitle($id){
        $query = "SELECT ProductTitle"
                . " FROM products"
                . " WHERE ProductID = ?";

        $bindArray = array($id);

        $query_result = $this->db->query($query, $bindArray);

        return $query_result->row()->ProductTitle;

    }

}

如果您想从网址中删除控制器名称,可以在/application/config/routes.php中创建自定义路由