swoole的异步mysql操作 swoole_mysql

异步mysql:swoole_mysql

class AsyncMysql{

	public $dbSource = '';
	public $dbConfig = '';

	public function __construct(){
		$this->dbSource = new Swoole\Mysql;
		$this->dbConfig= [
			'host'=>'127.0.0.1',
			"port"=>3306,
			"user"=>"root",
			"password"=>"root",
			"database"=>"test",
			"charset"=>'utf8',
		];
	}

	public function update(){

	}

	public function add(){
	
	}

	public function execute($id,$mark){
	    $this->dbSource->connect($this->dbConfig,function($db,$result){
                echo 'mysql Connect'.PHP_EOL;  
		 if($result === false){
                            var_dump($db->connect_error);
                            exit;
                   }
  
                   $sql = 'select * from test';
                   $db->query($sql,function($db,$result){
              	     if($result ===false){
                              echo 'query false';
                	 }elseif($result ===true){
                              echo 'query ok';
                  	 }else{
                              print_r($result);
                  	 }
                   $db->close();
              });
           });
	return true;

	}

}


$my = new AsyncMysql();

$res = $my->execute(1,1);
var_dump($res);
echo 'this is ok?';


运行结果:

这bool(true)
this is ok?mysql Connect
Array
(
[0] => Array
(
[mark] => 520
[victory] => a
)
[1] => Array
(
[mark] => 519
[victory] => a
)
)

小总结:异步操作数据库内容会在最后被执行,可以运用到页面记录、用户登录更新等操作。
异步执行操作数据记录,既不影响用户的访问速度,又把统计给做了,岂不是美滋滋!

你可能感兴趣的:(PHP基础知识,PHP7,swoole)