对数据的读取 Read
$m=new Model('User'); ##返回一个实例
$m=M('User');
select
#调用实例下的方法
$m->select();//获取所有数据,以数组形式返回
array (size=2)
0 =>
array (size=3)
'id' => string '1' (length=1)
'username' => string 'zhaotongzheng' (length=13)
'sex' => string '1' (length=1)
1 =>
array (size=3)
'id' => string '2' (length=1)
'username' => string 'MM' (length=2)
'sex' => string '0' (length=1)
find 方法:
find
$m->find($id);//获取单条数据
获取第一行数据,只返回一条数据
$arr=$m->find();
var_dump($arr);
获取Id=2的数据
$arr=$m->find(2);
var_dump($arr);
<?php
class IndexAction extends Action {
function index(){
#$m=new Model('user');
$m=M('user');
#$arr=$m->select();
$arr=$m->find();
var_dump($arr);
#$this->assign('data',$arr);
#$this->display();
}
array (size=3)
'id' => string '1' (length=1)
'username' => string 'zhaotongzheng' (length=13)
'sex' => string '1' (length=1)
find 只返回一条数据://获取单条数据
getField(字段名)//获取一个具体的字段值
$arr=$m->where('id=2')->getField('username');
添加数据:
对数据的添加 Create
$m=new Model('User');
$m=M('User');
$m->字段名=值
$m->add();
返回值是新增的id号
$m->id=3;
$m->username='scan';
$m->sex=1;
$m->add();
array (size=3)
0 =>
array (size=3)
'id' => string '1' (length=1)
'username' => string 'zhaotongzheng' (length=13)
'sex' => string '1' (length=1)
1 =>
array (size=3)
'id' => string '2' (length=1)
'username' => string 'MM' (length=2)
'sex' => string '0' (length=1)
2 =>
array (size=3)
'id' => string '3' (length=1)
'username' => string 'scan' (length=4)
'sex' => string '1' (length=1)
SHOW COLUMNS FROM `user` [ RunTime:0.004057s ]
INSERT INTO `user` (`id`,`username`,`sex`) VALUES (3,'scan',1) [ RunTime:0.173630s ]
SELECT * FROM `user` [ RunTime:0.001673s ]
删除数据:
$m->where('id=2')->delete(); //与上面效果相同,也是删除id为2的数据
更新数据:
$m=M('User');
$data['id']=1;
$data['username']='ztz2';
$m->save($data);
返回值是受影响行数
<?php
class IndexAction extends Action {
function index(){
#$m=new Model('user');
$m=M('user');
$arr=$m->select();
var_dump($arr);
$data['id']=1;
$data['username']='ztz2';
$m->save($data);
$arr=$m->select();
var_dump($arr);
#$this->assign('data',$arr);
$this->display();
}
array (size=2)
0 =>
array (size=3)
'id' => string '1' (length=1)
'username' => string 'ztz2' (length=4)
'sex' => string '1' (length=1)
1 =>
array (size=3)
'id' => string '2' (length=1)
'username' => string 'MM' (length=2)
'sex' => string '0' (length=1)
array (size=2)
0 =>
array (size=3)
'id' => string '1' (length=1)
'username' => string 'ztz2' (length=4)
'sex' => string '1' (length=1)
1 =>
array (size=3)
'id' => string '2' (length=1)
'username' => string 'MM' (length=2)
'sex' => string '0' (length=1)