天天看點

PHP:ThinkPHP5資料庫操作增删改查-Db類1、資料庫配置2、擷取資料表對象3、查詢資料4、插入資料5、更新資料6、删除資料7、條件構造器鍊式操作

項目檔案目錄

project/
    -app
    -conf      

1、資料庫配置

方式一 配置檔案

conf/database.php

<?php

return [
    'type'            => 'mysql',
    'hostname'        => '127.0.0.1',
    'database'        => 'root',
    'username'        => 'root',
    'password'        => '123456',
    'hostport'        => '3306',
    'charset'         => 'utf8'
];
      

方式二:控制函數

app\index\controller\Index.php

namespace app\index\controller;

use think\Db;


class Index
{
    public function index()
    {
        $db = Db::connect([
            'type' => 'mysql',
            'hostname' => '127.0.0.1',
            'database' => 'root',
            'username' => 'root',
            'password' => '123456',
            'hostport' => '3306',
            'charset' => 'utf8'
        ]);
        dump($db);

    }
}

      

方式三 DSN方式 Data Source Name

$db = Db::connect('mysql://root:[email protected]:3306/demo#utf8');      

方式四 從讀取配置

conf/config.php

<?php

return [
    'db_config' => [
        'type'            => 'mysql',
        'hostname'        => '127.0.0.1',
        'database'        => 'root',
        'username'        => 'root',
        'password'        => '123456',
        'hostport'        => '3306',
        'charset'         => 'utf8'
    ]
];      
$db = Db::connect('db_config');

// 或者
use  think/Config;

$db = Db::connect(Config::get('db_config'));      

2、擷取資料表對象

$bd = Db::table('pre_user')  # Db是單例模式
$bd = Db::name('user')  # 會自動添加字首

# 助手函數 db 每次調用執行個體化false取消每次執行個體化
$bd = db('pre_user', [], false)        

3、查詢資料

// 檢查資料庫配置
dump(config('database'));

// 使用sql語句查詢
$res = Db::query("select * from student");
$res = Db::query("select * from student where id=?", [1]);

// 插入資料 傳回影響條數
$res =Db::execute("insert into student set name=?, age=?", ['Tom',23]);

// select 傳回所有記錄 二維數組 []
$res = Db::table('student')->select();

// column 傳回所有列記錄 二維數組 NULL
# 如果存在第二個參數,為key值
$res = Db::table('student')->column('age', 'name');

// find 傳回一條記錄 一維數組 NULL
$res = Db::table('student')->find();

// value 傳回一條記錄中的某個字段 NULL
$res = Db::table('student')->value('name');
      

4、插入資料

$db = Db::table('student');

#insert 傳回值是影響記錄的行數,插入數
$res = $db->insert([
            'name' => 'Tom',
            'age' => 23
        ]);

#insetGetId 傳回值插入資料的自增id
$res = $db->insertGetId([
            'name' => 'Tom',
            'age' => 23
        ]);

#insertAll 傳回插入資料成功的行數
$data = [];
for ($i=0; $i<10; $i++)
{
    $data[] = [
        'name' => "Tom{$i}",
        'age' => 23
    ];
};

$res = $db->insertAll($data);      

5、更新資料

# update 更新多個字段 傳回影響行數
$res = $db->where([
        'id'=>1
    ])->update([
        'name'=> '王小二'
    ]);

# setField 更新一個字段 傳回影響行數
$res = $db->where([
        'id' => 1
    ])->setField('name', '王大錘');

# setInc 自增 傳回影響行數
$res = $db->where([
        'id' => 1
    ])->setInc('age');

# setDec 自減 傳回影響行數
$res = $db->where([
        'id' => 1
    ])->setDec('age');      

6、删除資料

# 條件删除,傳回影響行數
$res = $db->where(
        ['id'=>1]
    )->delete();

# 傳入主鍵删除 傳回影響行數
$res = $db->delete(2);

# 清空資料
$res = $db->where('1=1')->delete();      

7、條件構造器

buildSql();傳回SQL語句

where(‘字段名’,‘表達式’,‘查詢條件’);

表達式 含義
EQ、= 等于(=)
NEQ、<> 不等于(<>)
GT、> 大于(>)
EGT、>= 大于等于(>=)
LT、< 小于(<)
ELT、<= 小于等于(<=)
LIKE 模糊查詢
[NOT] BETWEEN (不在)區間查詢
[NOT] IN (不在)IN 查詢
[NOT] NULL 查詢字段是否(不)是NULL
[NOT] EXISTS EXISTS查詢
EXP 表達式查詢,支援SQL文法
> time 時間比較
< time
between time
notbetween time

示例

$db->where()->buildSql();

# 構造條件
$res = $db
    ->where('id', 'in', [1, 2, 3])
    ->whereOr('id', '<', '4')
    ->buildSql();

// string(62) "( SELECT * FROM `student` WHERE  `id` IN (1,2,3) OR `id` < 4 )"
      

鍊式操作

$res = Db::table('user')
    ->where('id', '>', 10)
    ->field('name', 'id')
    ->order('id DESC')
    // ->limit(3, 5)
    // ->page(3, 5)  // limit((3-1)*5, 5)
    ->group('`group`')
    ->select();