Reputation: 141
I'm trying to do is when i clicked my specific product, instead of the id of my product would appear in my url, i want to put the name of the product . what i did today is base_url/controller/method/id
i want to do is base_url/controller/method/product-name or base_url/controller/method/product_name
but in my code what happened is in my product name all the spaces is occupied by %20 what should i do to replace the %20 by either underscore or dash or whatever safe way to call the product name in url.
and whatever i get on that $name(product_name) i will pass it to my model.
MY CONTROLLER
public function details($name){
$prod_row = $this->PromoModel->getpromorow($name);
$data['promodetail'] = $prod_row;
$data['promo'] = $this->PromoModel->get_promo();
$data['message']= "<h1> NO PROMOS AVAILABLE</h1>";
$this->load->view('include/header',$data);
$this->load->view('include/nav');
$this->load->view('promo/PromoDetail', $data);
$this->load->view('include/footer');
}
MY MODEL
public function getpromorow($name) {
$this->db->where('name', $name);
$query = $this->db->get('promo');
return $query->row();
}
public function get_promo(){
$query = $this->db->get('promo');
return $query->result();
}
MY VIEW
<a href="<?= base_url(). 'promos/details/' . $promo_row->name ?>"> </a>
Upvotes: 0
Views: 4144
Reputation: 107
Late to the party. But best would be to use urldecode($value)
. Since "%" from "%20" gets encoded again to "%25", we might have to use urldecode
twice. In this case - urldecode(urldecode($promo_row->name))
Upvotes: 0
Reputation: 21661
This should work,
<a href="<?= base_url(). 'promos/details/' . str_replace(' ', '_', $promo_row->name); ?>"> </a>
As far as -
vs _
if you are routing to them, for example say that product name becomes a method in your controller, I don't think PHP allows -
in method names, but it doesn't allow spaces either.. You can cheat using __call()
but that's a other story for a different day.
If its a parameter, then it shouldn't matter as much. Just if it is a method/function name.
-Note- this is not a CI specific error, look at any url, tell me if you see spaces in them.
UPdate: as a suggestion the best way to handle this is by having a field dedicated to the url name ( such as slug
or such ) and when a new product is made just do the transform on the name. Then it's an editable piece of data you have control over. For example what if you have a product with a -
in it's name. This will probably cause issues. You can avoid that by having a separate piece of data just for that, it could even be like a SKU number etc. It's more work to setup, but in the long run more maintainable.
Upvotes: 1