没有链接数据库的例子:
![](https://box.kancloud.cn/c313ee1eb12dc23271345bc299f3c1c7_961x671.png)
`域名/index.php/控制器/方法`
CI的网址,反而相当于laravel的路由
没有链接数据库的foreach循环输出例子:
![](https://box.kancloud.cn/49a8e0e932e141d44651266dd0a7e670_1515x806.png)
原生php链接数据库例子:
![](https://box.kancloud.cn/1593d3146764348262de8ecde0efa4a3_1908x705.jpg)
链接数据库的foreach和for循环:
![](https://box.kancloud.cn/6036fbd8ce1aba69e91ba4f35b0e5d93_1907x1038.jpg)
代码如下:
~~~
//controllers, films.php
<?php
class Films extends CI_Controller{
public function display($offset = 0){
$limit = 20;
$this->load->model('Film_model');
$results = $this->Film_model->search($limit, $offset);
$data['films'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
$this->load->view('films', $data);
}
}
//models, film_model.php
<?php
class film_model extends CI_Model{
public function search($limit, $offset){
// result query
$q = $this->db->select('id, firstname, lastname')
->from('user')
->limit($limit, $offset);
$ret['rows'] = $q->get()->result();
//count query
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('user');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
}
//views, films.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<h1>Found <?php echo $num_results; ?> films</h1>
</div>
<table border="1">
<tr>
<?php for ($x=0; $x<=$num_results; $x++) { ?>
<th>
<?php echo "数字是:$x <br>"; ?>
</th>
<?php } ?>
</tr>
</table> <hr/>
<table border="1">
<thead>
<th>id</th>
<th>firstname</th>
<th>lastname</th>
</thead>
<tbody>
<?php foreach($films as $film): ?>
<tr>
<th><?php echo $film->id; ?></th>
<th><?php echo $film->firstname; ?></th>
<th><?php echo $film->lastname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
~~~
链接数据库简单一些的例子:
![](https://box.kancloud.cn/10cf73daa5a9053c1e1dc7bc74c8bf29_1881x1037.jpg)
代码如下:
~~~
//controllers, customer.php
<?php
class Customer extends CI_Controller{
public function __construct(){
parent:: __construct();
//load view
$this->load->model('Customer_model', 'customer');
}
public function index(){
$result = $this->customer->getCustomer();
if(!empty($result)){
$data['customers'] = $result;
$this->load->view('view_customer', $data);
}
}
}
//models, customer_model.php
<?php
class Customer_model extends CI_model{
public function getCustomer(){
$query = $this->db->get('user');
return $result = $query->result();
}
}
//views, view_customer.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>display data</h1>
<table border="1">
<thead>
<th>id</th>
<th>firstname</th>
<th>lastname</th>
</thead>
<tbody>
<?php foreach($customers as $film): ?>
<tr>
<th><?php echo $film->id; ?></th>
<th><?php echo $film->firstname; ?></th>
<th><?php echo $film->lastname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
~~~
源码下载:
链接:https://pan.baidu.com/s/1TFbtsQHam7oRliH6wX118g 密码:b97u