Codeigniter视图显示0记录

时间:2012-10-12 00:40:41

标签: php codeigniter activerecord foreach

我在ms_kategori_material表格中插入5行,并在此处制作了一些模型

function read()
{   
    $query = $this->db->get('ms_kategori_material');

    if($query->num_rows()>0)
    {            
        foreach ($query->result_array() as $value) {
            echo $value['Kode_Kategori_Material_Jasa'];
            echo $value['Nama_Material_Jasa'];
        }
        return $value;
    }
    else
    {
        return null;
    }
}

和控制器

function index()
{
      $data['kirim'] = $this->m_kategorimaterial->read();
      echo $data; //returns KKMJ001batuKKMJ002batuKKMJ003batuKKMJ004batuKKMJ005batuArray
      $this->load->view('v/vkategorimaterial',$data);

}

和观点

<?php  
                if ( !empty($kirim) ) {  
                 $no = 1;   
                 foreach ($kirim as $row) { ?>  
                 <tr id="row">  
                  <td id="no"><?php echo $no;?></td>  
                  <td id="judul"><?php echo $row->Kode_Kategori_Material_Jasa;?></td>  
                  <td id="kategori"><?php echo $row->Nama_Material_Jasa;?></td>  
                    </tr>  ?>
                    <?php  
                     $no++;  
                    }  
                   } else { ?>  
                                <tr id="row">  
                                <td colspan="6" align="center">Data tidak ditemukan</td>  
                               //the screen shows 'data tidak ditemukan' </tr>  
                            <?php  
                   }  
                   ?>  

这是如此令人困惑,因为我可以在控制器中看到数据,然后将它们传递到视图中,视图说没有收到数据

3 个答案:

答案 0 :(得分:4)

model

if($query->num_rows()>0)
{            
    foreach ($query->result_array() as $value) {
        echo $value['Kode_Kategori_Material_Jasa'];
        echo $value['Nama_Material_Jasa'];
    }
    return $value;
}

这是错的,应该是

if($query->num_rows()>0)
{            
    return $query->result();
}

并在controller中你应该

function index()
{
  $this->load->model('m_kategorimaterial'); // load it if it's not autoloaded
  $data['kirim'] = $this->m_kategorimaterial->read();
  $this->load->view('v/vkategorimaterial',$data);
}

答案 1 :(得分:1)

重新阅读您的代码。你正在返回$ value但从未填充它。见下文。

{   
    $query = $this->db->get('ms_kategori_material');

    if($query->num_rows()>0)
    {            
        $value = $query->result(); // or result_array() but you're using it as an object in the view not an array.
        return $value;
    }
    else
    {
        return null;
    }
}

答案 2 :(得分:1)

您实际上没有在模型中返回结果,

替换

foreach ($query->result_array() as $value) 
{
 echo $value['Kode_Kategori_Material_Jasa'];
 echo $value['Nama_Material_Jasa'];
}

<强>与

if($query->num_rows()>0)
{            
  return $query->result();
}