system 是框架核心php
application 是项目目录html
index.php 是项目入口文件mysql
其余目录能够删除web
控制器命名规则sql
控制器不加 Controller 后缀,数据库
如 user.php 这就是一个控制器数组
修改默认控制器和方法php框架
默认控制器是welcome.php,不喜欢能够改掉。app
修改方法以下:框架
在 config/routes.php 中
$route['default_controller'] = 'welcome';
改成
$route['default_controller'] = 'index/home';
为何不应成“index/index”呢???
由于CI中的控制器命名中没有后缀,因此index类的index方法会默认为析构方法__construct();
因此不能够这样搞,若是改为"index/index"则index方法会被调用两次。
加载视图文件
$this->load->view('index/home');
这个视图文件放在/application/view/index/home.php
看到这个文件的后缀了吗?它是一个php文件,不是html文件
在CI中 view() 方法能够使用屡次,也就是能够加载多个模板
能够这样写:
1.在 /application/view/index目录下有这样几个模板文件
header.php
main.php
footer.php
2.在index控制器的home方法中
1
2
3
4
5
6
|
public
function
home(){
//按顺序加载模板文件
$this
->load->view(
'index/header'
);
$this
->load->view(
'index/main'
);
$this
->load->view(
'index/footer'
);
}
|
给模板分配变量
CI框架中的模板是直接写php代码的,如分配一个hello的变量:
$this->load->vars('hello','heheheh');
在模板中直接写 <?php echo $hello;?>变量将变量输出。
还能够这样:
$data['hello'] = 'hello xxoo---';
直接写入关联数组
$this->load->vars($data);
在模板中关联数组健名就是模板里的变量名
<?php echo $hello; ?>
CI超级对象($this)中的装载器load
文件在system/core/loader.php,被实例化成一个属性
$this->load 属性是常常用到的,这里有几个经常使用的方法
$this->load->view()
$this->load->vars()
$this->load->database()
$this->load->model()
还能够这样写
1
2
3
4
|
$data
[
'one'
] =
'one'
;
$data
[
'two'
] =
array
(1,2,3,4,5);
//加载模板并分配变量
$this
->load->view(
'user/user'
,
$data
);
|
获取url中的参数$this->uri
文件在system/core/URI.php
如:url为 localhost/CodeIgniter/index.php/index/home
echo $this->uri->segment(1);
输出为:index
还能够这样
url为:http://localhost/CodeIgniter/index.php/index/home/1
public function home($id){
echo $id;
}
输出 1
多个参数一样,只不过顺序有限制
输入对象 $this->input
类文件目录同上
$this->input->post('username');//同$_POST['username'];
$this->input->server('HTTP_REFERER');//同$_SERVER[HTTP_REFERER'']
$this在视图中也能够使用
关于数据库的操做
pdo设置
在application/config/database.php 中找到并填写成以下:
$db['default'] = array(
'dsn'=> 'mysql:host=localhost;dbname=test;port=3306',
'hostname' => '',
'username' => 'root',
'password' => '123456',
'database' => '',
'dbdriver' => 'pdo',
);
// 设置默认加载的数据库的配置
$active_group = 'default';
$query_builder = TRUE;
// 这个数组能够有多个,不一样数据库填写不一样数组名称
$db['default'] = array(
);
$db['hello'] = array(
);
从数据库中获取数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
function
home(){
// 1.转载数据库操做类
$this
->load->database(
'default'
);
//默认为default能够不写
$sql
=
"select id,title from article limit 10"
;
// 2.执行sql
$obj
=
$this
->db->query(
$sql
);
// 3.获取结果集
$data
=
$obj
->result();
echo
"<pre>"
;
var_dump(
$data
);
}
|