thinkphp5的数据库操作

1. 数据库配置



2. query execute原生态sql语句 增删改查

$result = Db::execute('insert into log(user_id, ip) values(1, 11231)');
dump($result);

$result = Db::query('select * from log');
echo '<pre>';
var_dump($result);

3. 参数绑定 命名占位符绑定

$str = 'insert into log(user_id, ip) values(?, ?)';
$result = Db::execute($str, [1, '12312']);

$result = Db::query('select * from log where id = ?', [4]);

//占位符
Db::execute('insert into log(user_id, ip) values(:user_id, :ip)', ['user_id'=>12, 'ip'=>'5555']);

4. 查询构造器

//添加:
Db::table('log')->insert(['user_id'=>1, 'ip'=>'654321']);

//更新
Db::table('log')
    ->where('id', 12)
    ->update(['user_id'=>123]);

//查询数据
$list = Db::table('log')
    ->where('id', 12)
    ->select();

//删除数据
Db::table('log')
    ->where('id', 10)
    ->delete();

查询表时不用加前缀的方法:

Db::name('log')->insert(['user_id'=>44, 'ip'=>5555]);


5. DB链式操作

支持链式查询的方法:

方法名

描述

select

查询数据库

find

查询单个记录

insert

插入记录

update

更新记录

dalete

删除记录

value

查询值

column

查询列

chunk

分块查询

count

聚合查询

6. 事物支持

//自动控制事物
Db::transaction(function (){
    Db::table('log')->delete(2);
    Db::table('log')->insert(['user_id'=>123]);
});

//手动控制事物的提交
//启动事物
Db::startTrans();
try {
    Db::table('log')
        ->where(2);
    Db::table('log')
        ->insert(['user_id' => 213]);
    Db::commit();
} catch (Exception $e){
    Db::rollback();
}



猜你喜欢

转载自blog.csdn.net/dancheng1/article/details/78886762