【PHP框架CodeIgniter学习】数据库操作

本文使用的是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这个对象;不过后来按照上面的方法解决了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值