Codeigniter:foreach方法或结果数组?? [型号+查看]

时间:2012-08-24 11:08:51

标签: php arrays codeigniter model foreach

我目前正在使用Framework Codeigniter关注从数据库查看数据的教程。我学习的方式有很多种。是否有更可行的方式 - 在视图文件中显示为数组还是使用'foreach'?任何意见都会有所帮助。

这是我使用两种方法的代码:

方法1型号:

function getArticle(){
    $this->db->select('*');
    $this->db->from('test');
    $this->db->where('author','David');
    $this->db->order_by('id', 'DESC');
    $query=$this->db->get();

    if($query->num_rows() > 0) {
        foreach ($query->result() as $row) {
            $data[] = $row;
        }
        return $data;
    }$query->free_result();
}

}

方法1查看文件:

 <?php foreach($article as $row){ ?>
        <h3><?php echo $row->title;  ?></h3>
        <p><?php echo $row->content;  ?></p>
        <p><?php echo $row->author;  ?></p>
        <p><?php echo $row->date; ?></p>
<?php } ?>

方法2型号: class News_model扩展了CI_Model {

function getArticle(){
    $this->db->select('*');
    $this->db->from('test');
    $this->db->where('author', 'David');
    $this->db->order_by('id', 'DESC');
    $query=$this->db->get();

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

方法2查看文件:

    <?php echo '<h3>' .$article['title'].'</h3>' ?>
    <?php echo '<p>' .$article['content']. '</p>' ?>
    <?php echo '<p>' .$article['author']. '</p>' ?>
    <?php echo '<p>'. $article['date']. '</p>' ?>

1 个答案:

答案 0 :(得分:13)

我会这样做:

<强>模型

function getArticle() {
    $this->db->select('*');
    $this->db->from('test');
    $this->db->where('author','David');
    $this->db->order_by('id', 'DESC');
    return $this->db->get()->result();
}

}

<强>控制器

function get_tests() {
    $data = array(
        'tests' => $this->mymodel->getArticle()
    }
    $this->load->view('myview', $data);
}

查看

<table>
    <?php foreach($tests as $test) { ?>
    <tr>
        <td><?php echo $test->title;?></td>
        <td><?php echo $test->content;?></td>
        <td><?php echo $test->author;?></td>
        <td><?php echo $test->date;?></td>
    </tr>
</table>

如果您希望使用数组而不是对象,请在模型更改行

中使用
return $this->db->get()->result();

return $this->db->get()->result_array();

并在视图中回显

<td><?php echo $test['title'];?></td>

P.S。

在您的代码中,您使用$query->free_result();但它甚至没有运行,因为当您使用关键字return之后,甚至都不会解析所有内容。无论如何都没有必要释放结果。

P.S.2。

您使用if($query->num_rows() > 0) {但没有else部分,这意味着它也没有必要。如果您不在视图中的foreach语句中返回任何行,则不会出现任何错误。