Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a data with redirect in codeigniter

In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect

$in=1;
redirect(base_url()."home/index/".$in);

and my index function is

function index($in)
{
    if($in==1)
    {

    }
}

But I'm getting some errors like undefined variables.
How can i solve this?

like image 606
robins Avatar asked Jun 21 '15 07:06

robins


People also ask

Can we send data with redirect in CodeIgniter?

The CodeIgniter URL Helper comes to the rescue with the redirect() function that performs a header redirect to the path you specify as a parameter. redirect('/login/form/', 'refresh'); Just make sure you load the URL Helper prior to expecting this to work.

Can we pass data in redirect?

Yes. If not passing the object, then passing the id so that the other function can retrieve it from the database.

Why CodeIgniter redirect not working?

Add base_url() in redirect function. Show activity on this post. redirect('Admin/index') was not working until I removed echo statement and print_r from the function. Your answer could be improved with additional supporting information.


2 Answers

Use session to pass data while redirecting. There are a special method in CodeIgniter to do it called "set_flashdata"

$this->session->set_flashdata('in',1);
redirect("home/index");

Now you may get in at index controller like

function index()
{
 $in = $this->session->flashdata('in');
 if($in==1)
  {

  }
}

Remember this data will available only for redirect and lost on next page request. If you need stable data then you can use URL with parameter & GET $this->input->get('param1')

like image 165
Rejoanul Alam Avatar answered Oct 08 '22 13:10

Rejoanul Alam


So in the controller you can have in one function :

$in=1;
redirect(base_url()."home/index/".$in);

And in the target function you can access the $in value like this :

$in = $this->uri->segment(3);   
if(!is_numeric($in))
{
  redirect();       
}else{
   if($in == 1){

   }
}

I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).

Hope that helps.

like image 23
Arizona2014 Avatar answered Oct 08 '22 14:10

Arizona2014