Home > Article > PHP Framework > What to do if workerman introduces db error
In order to achieve more efficient server access speed, we will use long connections of mysql or other databases to improve access speed.
The following content uses mysql pdo as an example:
Problem:
When the cli is resident in memory, there will be many situations that cause the created connection to fail;
Solution:
When accessing the database When adding try catch capture
When the error captured is 2006 or 2013, it means that the connection has failed. Reconnect to the database at this time to ensure the normal operation of the program;
// 在和数据库交互的地方加上try catchpublic function Init($query) { try{ // todo 这里是操作数据库的逻辑 }catch (\Exception $e) { if ( $e->errorInfo[1] === 2006 || $e->errorInfo[1] === 2013 ) { // todo 下面填写 或者调用连接数据库的代码 $dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' . $this->settings["host"] . ''; $this->pdo = new \PDO($dsn, $this->settings["user"], $this->settings["password"], array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8;")); $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true); return true; } } }
var_dump($e-> ;errorInfo); The value
array(3) { [0]=> string(5) "HY000" [1]=> int(2006) [2]=> string(26) "MySQL server has gone away"}
For more workerman knowledge, please pay attention to the workerman tutorial column on the PHP Chinese website.
The above is the detailed content of What to do if workerman introduces db error. For more information, please follow other related articles on the PHP Chinese website!