2

currently I have a page like the following - abc.com/controller/action/23 Here 23 is Item id,which is dynamic. I have to fetch the name of the item using the id from database and route to a new url like following - abc.com/controller/p/23-itemname. How can I do that?

2 Answers 2

1

what you can do is when the user visits this page:

abc.com/controller/action/23

You put this code into the controller

CONTROLLER

function action()
{
    $id = $this->uri->segment(3); //id is now 23, this is the third uri
    $data['details'] = $this->YOUR_MODEL->get_details($id);
    foreach($data['details'] as $d)
    {
        $itemname = $d->YOUR_TABLE_COLUMN_NAME;
    }
    redirect(base_url(). 'controller/p/' . $id . '-' . $itemname);
    //line produces abc.com/controller/p/23-itemname
}

MODEL

function get_details($id)
{
    $this->db->select('*');
    $this->db->from('YOUR_TABLE_NAME');
    $this->db->where('YOUR_ID_COLUMN_NAME',$id);
    $query = $this->db->get();
    return $query->result();
}

Just comment if you need more clarifications.

Goodluck meyt

EDIT

Since you have action and you redirect to function p, here is what will happen.

function p()
{
    $explodethis = $this->uri->segment(3); //Contains "23-itemname"
    $pieces = explode("-", $explodethis); //Separate by the dash
    $id = $pieces[0];                     //Contains "23"
    $itemname = $pieces[1];               //Contains "itemname"

    $data['details'] = $this->YOUR_MODEL->YOUR_FUNCTION(YOUR_PARAMETERS)
    $this->load->view('YOUR_VIEW',$data);
}
Sign up to request clarification or add additional context in comments.

2 Comments

ok. But I have query . I f I use your code where should I use load view . In action() or in p()?
so in short, you load it in p since it is the last thing you load, if you try to load in action, it will only show for a short period of time until p is ready then fire p :D
0

Routing not required to do this. You may generate link by item name

<a href="<?php echo  site_url('controller/action').'/'.$val['item_id'].'-'.$val['item_name']; ?>"

and now in controller explode this title to get ID of the item and then execute your query

$title = explode('-','23-item-name');
$id = trim($title[0]);//this is your item ID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.