在codeigniter模型中为foreach()提供的参数无效

时间:2016-07-29 10:22:01

标签: php database codeigniter

function mostViewedTracks() {
    $this->load->database();        
    $this->db->select("*");
    $this->db->from("file");
    $this->db->order_by("views", "desc");
    $this->db->limit(8);
    $query = $this->db->get();
    if($query->num_rows() > 0)
    {
        $results = $query->result();
    }
    return array();
}

当我运行这个模型时,它给出了为foreach()

提供的无效参数的错误

这是我的观看代码:

    <?php if( !empty($most_viewed) ) { ?>
    <?php foreach($most_viewed as $row): ?>
    <a href="<?php echo base_url('index.php/home/track');?>/<?php echo $row->id;?>" class="list-group-item">
    <img class="track-list-img" src="<?php echo base_url('assets/img/music');?>/<?php echo $row->id;?>.jpg">
    <div class="list-track-infoo">
    <h4 class="list-group-item-heading"><?php echo $row->title;?><span class="badge"><?php echo $row->views;?><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span></span> </h4>
    <p class="list-group-item-text"><?php echo $row->singer;?></p>
    </div>
    </a>
    <?php endforeach; ?>
    <?php} ?>

已更新

控制器

function track() {
    $id = $this->uri->segment(3);
    $data1['track'] = $this->view_models->track($id);
    $data1['most_viewed'] = $this->view_models->mostViewedTracks();
    $this->load->view('includes/header');
    $this->load->view('track', $data1);
    $this->load->view('includes/footer');
}

我尽力解决这个问题,但一切都是徒劳的

3 个答案:

答案 0 :(得分:1)

而不是return array();,您必须从模型文件

返回结果集
  if($query->num_rows() > 0)
    {
         return $query->result();// return result set 
    }else{
          return FALSE;//
    }

在IN控制器中,您必须将模型功能调用为

$data1['most_viewed'] = $this->view_models->getFeaturedTracks();// change mostViewedTracks to getFeaturedTracks

在视图中将其用作

 <?php foreach($most_viewed as $row): ?>// remove $row1 to $row

答案 1 :(得分:1)

你需要改变两个错误,

You should return the `$result` array in your model like,

$results = $query->result();
return $results;

并在foreach中将$row1更改为$row,从而产生错误。见,

<?php foreach($most_viewed as $row): ?>

答案 2 :(得分:0)

功能应该是这样....

function getFeaturedTracks() {
    $results = array();
    $this->load->database();        
    $this->db->select("*");
    $this->db->from("file");
    $this->db->order_by("views", "desc");
    $this->db->limit(8);
    $query = $this->db->get();
    if($query->num_rows() > 0)
    {
        $results = $query->result();
    }
    return $results;
}