CI框架MySQL查询 [英] CI framework MySQL query
问题描述
我第一次使用CI框架,我需要一些帮助。
I am using CI framework for the first time, and I need some help.
我正在将一个现有网站迁移到CI框架,并遵循CI的教程一步一步,没有太多的麻烦,但有几个路障我似乎不能过去...
I am migrating an existing website over to the CI framework and have followed CI's tutorials step-by-step without much trouble, but there are a few roadblocks I can't seem to get past...
我的数据库表有2列 - 国家和city - 并且我想在视图文件中返回一个结果,该视图文件按国家/地区分组所有行,将该国家/地区作为标题打印,然后将所有相应的城市作为相关国家/地区下的列表打印。
My database table has 2 columns - "country" and "city" - and I want to return a result in the view file that groups all rows by country, prints that country as a header, and then prints all corresponding cities as a list beneath the relevant country.
Ie。
<h1>England</h1>
<ul>
<li>Liverpool</li>
<li>London</li>
<li>Sheffield</li>
</ul>
而在没有CI框架的情况下,我可以只写一个查询,返回一个结果,重新定义一个变量抛出几个if语句来实现期望的结果 - CI的mvc结构阻止我这样做...
Whereas before without CI framework, I could just write a query, return a result, redefine a variable and throw in a few if statements to achieve the desired result - the mvc structure of CI prevents me from doing so...
我收集这个秘密的关键在于控制器和创建某种数组来管理数据和在视图文件中使用 - 可以有人请帮我举个例子吗?
I gather the key to this mystery lies in the controller and creating some sort of array to manage the data and use in the view file - can somebody please help me with an example?
我现有的控制器是:
<?php
class Home extends CI_Controller {
public function index()
{
$this->load->model('Default_model');
$data['query'] = $this->Default_model->getResults();
$this->load->view('page_view', $data);
}
}
现有视图文件是:
<?php if (isset($query)):?>
<?php foreach ($query as $row):?>
<h1><?=$row->country?></h1>
<ul>
<li><?=$row->city?></li>
</ul>
<?php endforeach;?>
<?php endif;?>
并且型号:
function getResults()
{
$query = $this->db->query('SELECT * FROM events GROUP BY country, city ORDER BY country, city');
return $query->result();
}
任何人都可以帮我举个例子,只是为了告诉我这种类型查询在CI mvc结构中处理?
Can anybody help me with an example, just to show me how this type of query is handled within the CI mvc structure?
目前,上述代码的返回结果是:
Currently, the returned result of the above code is:
<h1>England</h1>
<ul>
<li>Liverpool</li>
</ul>
<h1>England</h1>
<ul>
<li>London</li>
</ul>
<h1>England</h1>
<ul>
<li>Sheffield</li>
</ul>
$ b
谢谢!
Thanks!
推荐答案
试一试
<?php
$country =$query[0]->country;
$index=1;
if (isset($query)):?>
<?php foreach ($query as $row):?>
<?php if($country==$row->country){
if($index==1){ ?>
<h1><?=$row->country?></h1>
<?php }
$index++;
}else{
$country=$row->country;
$index++;
?>
<h1><?=$row->country?></h1>
<?php } ?>
<ul>
<li><?=$row->city?></li>
</ul>
<?php endforeach;?>
<?php endif;?>
这篇关于CI框架MySQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!