【问题标题】:Display $query->result();显示 $query->result();
【发布时间】:2013-08-16 05:59:55
【问题描述】:

我在使用 codeigniter 中的 foreach 循环显示查询结果时遇到了一些问题。这是我的控制器:

function viewall()
{
    $this->load->model('all');
    $data['query'] = $this->all->viewall();
    $this->load->view('all', $data);
}

整个模型文件:

<?php
class All extends CI_Model
{

function insert_into_db()
{
    $data = array('Error' => $this->input->post('f1'),
                  'Solution' => $this->input->post('f2')
                 );
    $this->db->insert('Errors', $data);
}

function viewall()
{
    $query = $this->db->select("Error, Solution")->from("Errors")->get();
    return $query->result();
}

}

我的观点(我认为问题出在哪里)

<table class="table table-striped">
    <thead>
        <tr>
            <td><h3>Error</h3></td>
            <td><h3>Solution</h3></td>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($query->result_array() as $entry) ?>
        <tr>
            <td><?php echo $entry->Error; ?></td>
            <td><?php echo $entry->Solution;?></td>
        </tr>
        <?php endforeach ?>
    </tbody>
</table>

【问题讨论】:

    标签: php mysql codeigniter twitter-bootstrap foreach-loop-container


    【解决方案1】:

    控制器:

    function viewall()
    {
        $this->load->model('all');
        $data['results'] = $this->all->viewall();
        $this->load->view('all', $data);
    }
    

    型号:

    function viewall()
    {
        $query = $this->db->select("Error, Solution")->from("Errors")->get();
        return $query->result();
    }
    

    查看:

    <table class="table table-striped">
        <thead>
            <tr>
                <td><h3>Error</h3></td>
                <td><h3>Solution</h3></td>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($results as $entry): ?>
            <tr>
                <td><?php echo $entry->Error; ?></td>
                <td><?php echo $entry->Solution;?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    

    【讨论】:

    • 我认为 OP 想要保留 $query-&gt;result(),因为 OP 访问的成员像 $entry-&gt;Error 而不是 $entry["Error"]
    • 是的,我宁愿把它当作一个对象来获取
    • @JakeOls 已经object。你不需要在 foreach 中使用result_array
    • 为什么foreach()后面有个:
    • @JakeOls 如果您使用了&lt;?php foreach ($query as $entry): ?&gt; 并且不起作用,请使用var_dump($query); 检查结果
    猜你喜欢
    • 1970-01-01
    • 2013-01-20
    • 2017-07-10
    • 1970-01-01
    • 2020-04-09
    • 2019-11-19
    • 1970-01-01
    • 2019-04-11
    • 2012-09-22
    相关资源
    最近更新 更多