如何从控制器返回查询中的数据

时间:2015-03-14 04:51:48

标签: php mysql codeigniter

我有一个关于如何将我在模型中查询的数据检索到控制器并在我的视图中传递的问题。

控制器:

class View_book_controller extends CI_Controller {

function __construct() {

    parent::__construct();
    $this->load->helper('cookie');
    $this->load->helper('url');
    $this->load->library('session');
}

function loadView() {
    $this->load->model('view_book_model');
    $postlist['studentID'] = $this->input->get_post('studentID');

    $this->view_book_model->getBookList();

    $this->load->view('viewbooks.php', $postlist);
 }
}

型号:

class View_book_model extends CI_Model {

function getBookList() {

    $query = $this->db->query("SELECT * from books");

    if($query->num_rows() > 0 ) {
        return true;
    }
    else {
        return false;
    }
}
}

以下是它的观点。我想把数据放在一个表中,然后像列表一样查看。

 <!DOCTYPE HTML>
 <html>

 <head>
 <meta charset='UTF-8'>

<link rel="stylesheet" href="<?=base_url(); ?>/public/css/tables.css"/>

<script src="<?=base_url()?>/public/js/jquery.js"></script>
 </head>

<body>
    <input type="hidden" value = "<?php echo $studentID; ?>"/>
    <h3> Search books </h3>
    <input type="text"> </input>
    <input type="submit" value="Search"> </input>
    <br><br>

    <?php
        echo '<hr>';
        echo '<h3> Book List </h3>';
        echo '<table id="maintable"  class="table">';

            echo '<th> Book ID</th>';
            echo '<th> Book Title </th>';
            echo '<th> Book Author </th>';
            echo '<th> Quantity </th>';
            echo '<th> On-hand </th>';

            echo '<tr>
                    <td>1</td>
                    <td>An Abundance of Katherine</td>
                    <td>John Green</td>
                    <td>10</td>
                    <td>5</td>
                 </tr>';
        echo '</table>';
    ?>
</body>
 </html>

1 个答案:

答案 0 :(得分:0)

<强>模型

首先,确保您的模型返回行。在您的代码中,您只返回布尔值而不是记录的数组对象。因此,您可以这样做:

Check how to generate result in codeigniter.

class View_book_model extends CI_Model {
    function getBookList() {
        $query = $this->db->query("SELECT * from books");

        return $query->result();
    }
}

<强>控制器

在你的控制器上,将模型记录存储在$postlist数组上,在我的例子中,我把它作为book_list例如,并将它传递给你的视图加载器。

class View_book_controller extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->helper('url');
        $this->load->library('session');
    }

    function loadView() {
        $this->load->model('view_book_model');

        $postlist['studentID'] = $this->input->get_post('studentID');
        $postlist['book_list'] = $this->view_book_model->getBookList();

        $this->load->view('viewbooks.php', $postlist);
     }
}

查看

在您的视图中,您可以使用$ postlist键作为变量名称检查行:

<? var_dump($book_list); ?>

您可以使用foreach打印HTML或使用内置的HTML Table Class codeigniter手动生成表。