codeigniter从数据库中获取数组

问题描述 投票:0回答:2

我是codeigniter的新手并且遵循指南,但似乎错过了一些东西。我有一个简单的数据库,里面有客户记录。我在codeigniter的第一个目标是简单列出我的所有客户。

这是我的控制器:

public function index()
{
    $this->load->model('HomeModel');    //loads the HomeModel model
    $data = $this->HomeModel->function1();       //loads the function (function1) from the model

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

这是我的模型:

public function function1()
{
$query = $this->db->get('work_orders');
return $query->result();

}

这是我的看法:

<table class="table table-bordered table-striped table-highlight" id="invoice-details">
    <thead>
     <tr>
      <th>Work Order ID</th>
      <th>Status</th>
      <th>Description</th>
     </tr>
    </thead>
    <?php
     foreach ($data->result() as $row);?>
      <tr class="even gradeC">
      <td><a href="/WorkOrders/viewWo/<?php  echo $row['id']; ?>">
      <?php  echo $row['id']; ?></a></td>
      <td><?php  echo $row['status']; ?></td>
      <td><?php  echo Logic\System\Lib\Helper::trunc(htmlentities($row['description']), 8); ?></td>
      </tr>
    <?php  endforeach; ?>
    </table>
codeigniter
2个回答
0
投票

改变型号:

public function function1()
{
    $query = $this->db->get('work_orders');
    //return $query->result();
    return $query->result_array();
}

更改控制器:

public function index()
{
    $this->load->model('HomeModel');    
    //$data = $this->HomeModel->function1(); 
    $data['result'] = $this->HomeModel->function1(); 
    $this->load->view('index', $data);
}

改变观点:

//foreach ($data->result() as $row);
    if(is_array($result)&&!empty($result))
        foreach ($result as $row);

数据通过视图加载函数的第二个参数中的数组或对象从控制器传递到视图。以下是使用数组的示例:

$data = array(
               'title' => 'My Title',
               'heading' => 'My Heading',
               'message' => 'My Message'
          );

$this->load->view('blogview', $data);

Views : Codeigniter User Guide

既然你在$row['id']这样的视图上使用数组,你必须在模型上使用result_array来返回结果集数组:

此函数将查询结果作为纯数组返回,或者在未生成结果时返回空数组。通常你会在foreach循环中使用它,如下所示:

$query = $this->db->query("YOUR QUERY");

foreach ($query->result_array() as $row)
{
   echo $row['title'];
   echo $row['name'];
   echo $row['body'];
}

Generating Query Results : Codeigniter

你可以使用$this->db->join();

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

生产:

SELECT * FROM blogs
JOIN comments ON comments.id = blogs.id

浏览活动记录类指南。 Active Record Class


0
投票

在你的控制器中,你必须将值作为数据array$data['result']的子数组传递。之后你可以简单地在视图中将其称为$result

调节器

$data['result'] = $this->HomeModel->function1();

并且在视野中,

foreach ($result as $row){
 <?php  echo $row->id; ?>
..
}
© www.soinside.com 2019 - 2024. All rights reserved.