没有链接数据库的例子:

`域名/index.php/控制器/方法`
CI的网址,反而相当于laravel的路由
没有链接数据库的foreach循环输出例子:

原生php链接数据库例子:

链接数据库的foreach和for循环:

代码如下:
~~~
//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>
~~~
链接数据库简单一些的例子:

代码如下:
~~~
//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