【问题标题】:codeigniter - pass data to viewcodeigniter - 将数据传递给查看
【发布时间】:2014-01-27 09:07:03
【问题描述】:

好的,我有一个简单的问题,我正在使用 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);

}


}

我不确定要为我的新视图做什么?我只是想将博客滚动回显到视图

【问题讨论】:

    标签: php codeigniter argument-passing


    【解决方案1】:

    嗯,你在返回函数之后在模型中做一个 foreach。

    所以你返回的只是这个:

    $query-&gt;result()

    您可能应该在视图中执行 foreach,这将更好地放置为模型应该只返回而不是处理信息。在这种情况下,最好的地方是控制器或可以查看 - 取决于您的严格程度。

    我有一段时间没有使用 CodeIgniter,所以可以试试这个: 控制器:

    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...
    

    你想查找this(CodeIgniter Doc)。

    希望这会有所帮助。试试看

    【讨论】:

      【解决方案2】:

      控制器:

      $data['blogs'] = $this->blog_model->get();
      

      即使您加载模型以调用其函数,您也必须传递其名称。

      型号:

      在应用查询时必须始终有result() 或row()。

      希望这对你的努力有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多