我目前正在学习使用Framework Codeigner从数据库中查看数据的教程。我的学习方式多种多样。有没有一种更现实的方式——要么显示为数组,要么在视图文件中使用"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模型:类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>' ?>
我会这样做:
型号
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>
第页。S.
在代码中,您使用$query->free_result();
,但它甚至不会运行,因为当您使用关键字return
时,之后的所有内容都不会被解析。无论如何都没有必要释放结果。
第页。S.2.
您使用了if($query->num_rows() > 0) {
,但没有else
部分,这意味着它也没有必要。如果在视图中foreach语句不返回任何行,则不会出现任何错误。