本文使用的是CodeIgniter 2.1.4版本,可能会与其他版本的代码不一样,请参考。
原文链接:http://www.leake86.net/blog/?p=50
一、配置你的数据库文件。
打开 application\config\database.php
配置以下字段
1
2
3
4
5
|
$db
[
'default'
][
'hostname'
] =
'localhost'
;
$db
[
'default'
][
'username'
] =
'root'
;
$db
[
'default'
][
'password'
] =
'root'
;
//数据库密码
$db
[
'default'
][
'database'
] =
'ltech'
;
//数据库名称
$db
[
'default'
][
'dbdriver'
] =
'mysql'
;
|
二、配置数据库类库自动加载
打开 application\config\autoload.php
最后一行加上 $autoload['libraries'] = array(‘database’);
不然的话会报错“Undefined property: XXX::$db”;
三、编写Model
我在mysql上新建数据库,叫”ltech”,新建一个表user,新建字段name,password;
然后插入一些测试数据用于后面使用。
在\application\models目录下,新建user_model.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php
if
(! defined(
'BASEPATH'
))
exit
(
'No direct script access allowed'
);
class
User_Model
extends
CI_Model
{
var
$name
=
''
;
var
$password
=
''
;
function
get_last_ten_entries()
{
$query
=
$this
->db->query(
'SELECT * FROM user ORDER BY id DESC LIMIT 10'
);
return
$query
->result();
}
}
?>
|
四、编写Controller
在\application\controllers目录下,新建usercontroller.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
class
UserController
extends
CI_Controller
{
function
index()
{
$this
->load->model(
'user_model'
);
$data
[
'result'
] =
$this
->user_model->get_last_ten_entries();
$data
[
'title'
] =
'Hello World Page Title'
;
$this
->load->view(
'user_view'
,
$data
);
}
}
?>
|
五、编写View
在\application\views目录下,新建user_view.php
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<html>
<head>
<title><?=
$title
?></title>
</head>
<body>
<h1>CodeIgniter Hello World Application</h1>
<table>
<?php
foreach
(
$result
as
$row
):?>
<p><tr><td><?=
$row
->name?>/<td><td><?=
$row
->password?></td></tr>
<?php
endforeach
;?>
</table>
</body>
</html>
|
然后运行http://localhost/CodeIgniter/index.php/usercontroller 就能看到结果了!
大功告成;
在【配置数据库类库自动加载】这部卡了很久,一直都找不到原因,一直提示没有找到db这个对象;不过后来按照上面的方法解决了。