How to pass variables from controller to view

2019-09-19 05:26发布

问题:

iam using codeigniter 2.2 The following is my controller class

class Welcome extends CI_Controller {


public function index()
    {
     $test = "hello";
     $this->load->view('welcome_message',$test);
 }
}

The following is my view

<html><body><h1><?php echo  $data?></h1></body></html>

trying to pass a variable to the view keep getting this error

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/welcome_message.php

Line Number: 75

回答1:

Try this,

class Welcome extends CI_Controller {


    public function index()
        {
            $test = "hello";
            $data['test'] = $test
            $this->load->view('welcome_message',$data);
        }
    }
}

in view

<html><body><h1><?php echo $test; ?></h1></body></html>

For more reference check https://ellislab.com/codeigniter/user-guide/general/views.html