我正在尝试从数据库获取所有数据并传递给视图 我在模型函数中创建了获取数据,它看起来像那样
public function get_data_from_db(){
$query = $this->db->get('posts');
return $query->result_array();
}
在视图中我创建了foreach循环,它看起来像:
<h6>Mjesto Odredista:
<?php if($posts): ?>
<?php foreach ($posts as $post): ?>
<div class="well">
<h5><?php echo $posts['mjestoOdredista'];?>
</div>
<?php endforeach;?>
<?php else : ?>
<?php endif;?>
</h6>
我将数据输入到我的视图中,但已经过了10次:
有人能解释我哪里弄错了吗?
答案 0 :(得分:0)
你的h5标签包含$ posts,应该是$ post。
<h6>Mjesto Odredista:
<?php if($posts): ?>
<?php foreach ($posts as $post): ?>
<div class="well">
<h5><?php echo $post['mjestoOdredista'];?>
</div>
<?php endforeach;?>
<?php else : ?>
<?php endif;?>
</h6>
答案 1 :(得分:0)
首先,我建议您将型号代码更改为此
public function get_data_from_db(){
//less lines of code, and using result() makes your loop easier
return $this->db->get('posts')->result();
}
然后您的视图将如下所示
<h6>Mjesto Odredista:
<?php if($posts){
foreach ($posts as $post): ?>
<div class="well">
<!--$post is an object, so u use the arrow to display it, instead of the [] for arrays
note that this only works if mjestoOdredista is a column name from your database, if not, use the column name to display the value -->
<h5><?=$post->mjestoOdredista?></h5>
</div>
<?php endforeach;
}else { ?>
//do something else
<?php } ?>
我希望这会帮助你。如果您发现任何困难,请告诉我,让我们解决一下。