Home > PHP Framework > Workerman > body text

How does workerman call the database?

Release: 2019-12-23 16:43:18
Original
3503 people have browsed it

How does workerman call the database?

Dependent extensions

The mysql class depends on two extensions, pdo and pdo_mysql. If the extension is missing, Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in . ...mistake.

Running php -m from the command line will list all php cli installed extensions

centos system

PHP5.x

yum install php-pdo
yum install php-mysql
Copy after login

PHP7.x

yum install php70w-pdo_dblib.x86_64
yum install php70w-mysqlnd.x86_64
Copy after login

Install Workerman/MySQL

Method 1:

can be installed through composer, run the following command on the command line (the composer source is abroad, the installation process may be very slow).

composer require workerman/mysql
Copy after login

After the above command is successful, the vendor directory will be generated, and then autoload.php under the vendor will be introduced into the project.

require_once __DIR__ . '/vendor/autoload.php';
Copy after login

workerman calls the database instance:

use Workerman\Worker;
require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:8484');
$worker->onWorkerStart = function($worker)
{
    // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
    global $db;
    $db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
};
$worker->onMessage = function($connection, $data)
{
    // 通过全局变量获得db实例
    global $db;
    // 执行SQL
    $all_tables = $db->query('show tables');
    $connection->send(json_encode($all_tables));
};
// 运行worker
Worker::runAll();
Copy after login

For more workerman knowledge, please pay attention to the workerman tutorial column.

The above is the detailed content of How does workerman call the database?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!