Codeiniter为查询返回空数组

时间:2017-01-19 19:20:46

标签: php codeigniter

我是Codeigniter的新手。我正在尝试从数据库表中加载一些记录。但总是返回一个空数组。

我的代码如下。

模型 - Hottopics_model

<?php
class Hottopics_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    public function get_hotpost($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('post');
            return $query->result_array();
        }

        $query = $this->db->get_where('post', array('slug' => $slug));
        return $query->row_array();
    }

}
?>

控制器 - Hottopics

<?php
class Hottopics extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('hottopics_model');
        $this->load->helper('url_helper');
    }

    public function index()
    {
        $data['hotpost'] = $this->hottopics_model->get_hotpost();

        $this->load->view('hottopics/index', $data);
    }

}
?>

查看

<?php if(!empty($hotpost)){ ?>

<div class="topics-carousel-wrapper">
    <span class="color2">Hot Topics</span>
    <div class="topics-carousel">
        <?php foreach ($hotpost as $row): ?>
            <div class="topic"><a href="single-post.html" title="">
                <?php echo $row->post_title; ?></a>
            </div>
        <?php endforeach; ?>
    </div>
</div><!-- Hot Topics -->

<?php } ?>

请帮我解决这个问题。感谢。

1 个答案:

答案 0 :(得分:0)

在您的视图中尝试使用此代码:使用$row['post_title']代替$row->post_title,因为数据是以数组格式传递的。

<?php if(!empty($hotpost)){ ?>

<div class="topics-carousel-wrapper">
    <span class="color2">Hot Topics</span>
    <div class="topics-carousel">
        <?php foreach ($hotpost as $row): ?>
            <div class="topic"><a href="single-post.html" title="">
                <?php echo $row['post_title']; ?></a>
            </div>
        <?php endforeach; ?>
    </div>
</div><!-- Hot Topics -->

<?php } ?>