今天说下easyswoole如何连接数据库,官网推荐使用easyswoole3.x的版本,这里我们采用mysqli来连接数据库

第一步、首先是确定PHP的mysqli的扩展已安装并开启(php.ini开启),我这边是用的php7.4,

我这边已经看到是有的,没有安装的小伙伴可以按如下步骤安装

1、找到源码包php-7.4.4中ext目录下的mysqli

2、输入 /usr/local/php74/bin/phpize

3、在mysqli文件夹下执行 ./configure --with-php-config=/usr/local/php/bin/php-config 

4、make 

5、make install

第二步、安装easyswoole的mysqli库

使用composer命令安装即可,composer require easyswoole/mysqli

安装成功以后,在vendor\easyswoole目录就可以看到刚刚安装的mysqli库

第三步、编码实现
1.首先在配置文件dev.php新增内容
/*################ MYSQL CONFIG ##################*/

'MYSQL' => [
'host' => '127.0.0.1',
'port' => '3306',
'user' => 'root',
'timeout' => '5',
'charset' => 'utf8',
'password' => 'root',
'database' => 'easyswoole',
'POOL_MAX_NUM' => '20',
'POOL_TIME_OUT' => '0.1',
],
下面是App\HttpController\Api\index.php内容
<?php
/**
* Create by PhpStorm
* User: 雷小天
* Site: www.100txy.com
* Date: 2020/4/1 0001
* Time: 21:33
*/

namespace App\HttpController\Api;

use App\HttpController\Api\Base;
use EasySwoole\Mysqli\Config;
use EasySwoole\Mysqli\Client;
use EasySwoole\EasySwoole\Config as Configs;

/**
* Class Index
* @package App\HttpController\Api\Base
*/
class Index extends Base
{

public function video()
{
$data = [
'id' => 1,
'name' => 'lei',
'params' => $this->request()->getRequestParam(),
];
return $this->writeJson(200, $data, 'ok');
}

/**
* client连接msyqli
* @return bool
* @throws \Throwable
*/
public function getVideo(){
$config=Configs::getInstance()->getConf('MYSQL');
$conf = new Config($config);
$db = new Client($conf);
$db->queryBuilder()->get('video');//获取一个表的数据
$data = $db->execBuilder();
return $this->writeJson(200, $data,'ok');

}

}