Home  >  Article  >  PHP Framework  >  How to use swoole and mysql

How to use swoole and mysql

angryTom
angryTomOriginal
2020-03-14 10:28:062709browse

How to use swoole and mysql

How to use swoole and mysql

swoole is better for asynchronous operation of MySQL.

Benefits of using asynchronous mysql:

Prevent code blocking and improve code efficiency

Applicable occasions:

1. No shared resources are involved, or shared resources are read-only, that is, non-mutually exclusive operations

2. There is no strict relationship in timing

3. No atomic operations are required, or they can be passed Other ways to control atomicity

4. Often used for time-consuming operations such as IO operations, because it affects customer experience and performance

5. Does not affect the main thread logic

Recommended Learning: MySQL video tutorial

## Code example:

<?php
class mysql {
    private $param;
    public $db;
    public function __construct() {
        $this->db = new swoole_mysql;
        $this->param = array(
            &#39;host&#39; => &#39;127.0.0.1&#39;,
            &#39;user&#39; => &#39;root&#39;,
            &#39;password&#39; => &#39;123&#39;,
            &#39;database&#39; => &#39;test&#39;,
        );
    }

    public function exec($sql) {
        $this->db->connect($this->param, function ($db, $result) use ($sql) {
            if ($result === false) {
                echo "连接数据库失败 : 错误代码:" . $db->connect_errno . PHP_EOL . $db->connect_error;
                return false;
            }
            $db->query($sql, function ($db, $res) {
                if ($res === false) {
                    // error属性获得错误信息,errno属性获得错误码 
                    echo "sql语句执行错误 : " . $db->error;
                } else if ($res === true) {
                    // 非查询语句  affected_rows属性获得影响的行数,insert_id属性获得Insert操作的自增ID 
                    echo "sql语句执行成功,影响行数 : " . $db->affected_rows;
                    
                } else {
                    //查询语句  $result为结果数组 
                    var_dump($res);
                    
                }
                $db->close();
            });
        });
    }
}

$mysql = new mysql();

PHP Chinese website, a large number of

website construction tutorials , welcome to learn!

The above is the detailed content of How to use swoole and mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn