我发誓我总是对CodeIgniter如何将控制器变量传递给他们的视图感到困惑,而我在其中执行的每个项目都会遇到同样的愚蠢问题。
这是我的模特:
public function get_post() {
$sql = "SELECT * FROM posts WHERE active='y' AND head=1 LIMIT 1";
$query = $this->db->query($sql);
return $query->row();
}
这是我的控制器:
public function get_head() {
$this->load->model('home_model');
$data['head'] = $this->home_model->get_post();
$this->load->view('home_view', $data);
}
当我在我的视图上执行var_dump($ head)时,我得到:
object(stdClass)#18 (16) { ["id"]=> string(1) "1" ["member_id"]=> string(1) "1" ["title"]=> string(131) "This is a test title" ["slug"]=> string(0) "this-is-a-test-title" ["body"]=> string(0) "" ["tag"]=> string(7) "singles" ["orig_photo_name"]=> string(142) "sample.jpg" ["photo"]=> string(24) "14004803271605326007.jpg" ["comments"]=> string(1) "y" ["post_date"]=> string(19) "2014-06-17 02:18:47" ["head"]=> string(1) "1" ["views"]=> string(2) "50" ["notes"]=> string(0) "" ["nsfw"]=> string(1) "y" ["active"]=> string(1) "y" }
最后,当试图访问类似标题的内容时:
<?php echo $title; ?>
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: title
Filename: views/home_view.php
Line Number: 8
除了切换到CakePHP之外的任何想法?
答案 0 :(得分:2)
$query->row()
将返回对象,因此请尝试访问视图
echo $head->id;
echo $head->title;
等等
答案 1 :(得分:0)
First You change the model query like this
public function get_post() {
$sql = "SELECT * FROM posts WHERE active='y' AND head=1 LIMIT 1";
$query = $this->db->query($sql);
return $query->row_array(); //this is return value in array
}
Then call function in Controller
public function get_head() {
$this->load->model('home_model');
$data['head'] = $this->home_model->get_post();
$this->load->view('home_view', $data);
}
Then get value in view
<?php echo $head['id']; ?>