PHP code example of scpzc / hyperf-db

1. Go to this page and download the library: Download scpzc/hyperf-db library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

scpzc / hyperf-db example snippets

regexp
$count = Db::table('user')->count($where,$params); #查询记录数
$userInfo = Db::table('user')->fetchRow($where,$params,$fields); #查询单条
$userList = Db::table('user')->fetchAll($where,$params,$fields); #查询多条
$username = Db::table('user')->fetchOne($where,$params,$fields); #查询某列
$result = Db::table('user')->fetchByPage($where,$params,$fields,$page,$pageSize); #查询分页
regexp
$userInfo = Db::fetchRow('SELECT username * FROM user_id=:user_id',['user_id'=>1]);
regexp
$order = 'id desc,age asc';  #支持字符串和数组
$order = ['id'=>'desc','age'=>'asc']; 
$userList = Db::table('user')->order($order)->fetchAll($where,$params,$fields);
regexp
$userList = Db::table('user')->limit($offset,$limit)->fetchAll($where,$params,$fields);
regexp
$data = ['username'=>'张三','age'=>10];
$id = Db::table('user')->insert($data); #返回自增ID,只支持单条
regexp
$data = ['username'=>'张三','age'=>10];
$where = ['user_id'=>1];
$result = Db::table('user')->update($data,$where); #返回修改记录数,失败返回false,修改0条返回0
regexp
$result = Db::table('user')->delete($where); #返回删除记录数
regexp
Db::table('user')->execute($sql,$params);
regexp
Db::connect('log')->table('user')->insert($data);
regexp
$where = ['user_id'=>1];
$where = [['user_id','=',1]];
$where = [
    ['user_id','>',1],
    ['user_id','<',10],
];
$where = [
    ['user_id','in',[1,2]],
    ['user_id','not in',[3,4]],
];
regexp
$where = "user_id = :user_id and age > :age";
$params = ['user_id'=>1,'age'=>10];
regexp
$sql = "SELECT username FROM user WHERE user_id = :user_id";
$params = ['user_id'=>1];
regexp

declare(strict_types=1);
namespace App\Listener;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Scpzc\HyperfDb\Event\FailToExecute;

#[Listener]
class FailToExecuteDbListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            FailToExecute::class,
        ];
    }
    /**
     * @param FailToExecute $event
     */
    public function process(object $event)
    {
        var_dump($event->throwable->getMessage());
    }
}

regexp
Db::table('user')->fetchRow($where); 
var_dump(Db::getSql()); #SQL语句会执行,如果有语法错误,可能不能输出
regexp
Db::table('user')->debug()->fetchRow($where); #SQL语句不会执行,会直接在控制台输出SQL语句
regexp
Db::startTrans()  #开始事务
Db::commit()  #提交事务
Db::rollBack()  #回滚事务