[英]codeigniter - pass data to view
好的,我有一个简单的问题,我正在使用codeigniter框架创建一个简单的博客。 当我只设置一个控制器和一个视图时,就可以将我的数据库信息(博客记录)打印到我的视图中。 当我使用模型控制器视图方法时,我将失败。
这是我想在方法控制器视图设置中实现的内容。
我原来的观点是可行的:
<?php
//is there an array from your search form?
if($_GET){
$books = $this->db->get('blog');//query the blog table in the database
if($books->num_rows() < 1)//are there clients to show?
{
echo 'There are no blog post'; //error message if no post
}
else
{
foreach(result() as $row)//loop through the blog
{
echo $row->title."<br>";//display each titles info
}
}
}
?>
这就是我为新模特设置的
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog_Model extends CI_Model {
function get($args = null)
{
$query = $this->db->get('blog');
return $query->result();
foreach(result() as $row)//loop through the books
}
function insert($data)
{
$this->db->insert('blog', $data);
}
function update($data,$id)
{
$this->db->where("id",$id);
$this->db->update('blog', $data);
}
function delete($id)
{
$this->db->where("id",$id);
$this->db->delete('blog');
}
}
这是我的新控制器
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog->get();
$this->load->view('blog',$data);
}
}
我不确定该如何处理新视图? 我只想在博客中反映出观点
好吧,在返回函数之后,您正在模型中进行一次foreach。
因此,您返回的就是:
$query->result()
您可能应该在视图中执行foreach,因为放置模型只是返回而不是处理信息,所以最好放置它。 在这种情况下,最好的位置是控制器或可以查看-取决于您的严格程度。
我有一段时间没有使用CodeIgniter,因此可以尝试以下方法: Controller :
class Blog extends CI_Controller
{
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog_model->get()->result();
$this->load->view('blog',$data);
}
}
视图
Here goes some text...
<?php
foreach($blogs as $post)
{
echo $post['someData'];
echo $post['someData2'];
}
?>
After all this code...
可能您想查找此代码 (CodeIgniter Doc)。
希望这可以帮助。 尝试
控制器:
$data['blogs'] = $this->blog_model->get();
即使加载模型以调用其函数,也必须传递其名称。
模型:
应用查询时必须始终具有result()
或row()
。
希望这对您的工作有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.