A
A
Abdulla Timershin2020-04-25 03:15:26
PHP
Abdulla Timershin, 2020-04-25 03:15:26

How to use live connection to mysql (Workerman\Mysql\Connection)?

I am using the walkor/Workerman library to create a websocket.
Also, this developer has the Workerman\Mysql\Connection library for live connection to the database.
Maybe someone who has worked with this can help.

require_once("workerman/vendor/autoload.php");
require_once("mysql/vendor/autoload.php");

// SSL context.
$context = array(
    'ssl' => array(
        'local_cert'  => '/your/path/of/server.pem',
        'local_pk'    => '/your/path/of/server.key',
        'verify_peer' => false,
    )
);

// Create a Websocket server with ssl context.
$ws_worker = new Worker('websocket://0.0.0.0:2346', $context);
$db = new Workerman\MySQL\Connection('host', "port", "user", "pass", "dbname");

// Enable SSL. WebSocket+SSL means that Secure WebSocket (wss://). 
// The similar approaches for Https etc.
$ws_worker->transport = 'ssl';

$ws_worker->onMessage = function ($connection, $data) {
    $query = $db->row("query text");
    // Send hello $data
    $connection->send('Hello ' . $data);
};

Worker::runAll();

So when a client connects and receives a message, i.e. onMessage, it displays an error that db = null

require_once("workerman/vendor/autoload.php");
require_once("mysql/vendor/autoload.php");

// SSL context.
$context = array(
    'ssl' => array(
        'local_cert'  => '/your/path/of/server.pem',
        'local_pk'    => '/your/path/of/server.key',
        'verify_peer' => false,
    )
);

// Create a Websocket server with ssl context.
$ws_worker = new Worker('websocket://0.0.0.0:2346', $context);
$db = new Workerman\MySQL\Connection('host', "port", "user", "pass", "dbname");
$query1 = $db->row("query text");

// Enable SSL. WebSocket+SSL means that Secure WebSocket (wss://). 
// The similar approaches for Https etc.
$ws_worker->transport = 'ssl';

$ws_worker->onMessage = function ($connection, $data) {
   $query2 = $db->row("query text");
    // Send hello $data
    $connection->send('Hello ' . $data);
};

Worker::runAll();

If you check and make a query at the beginning, then in query1 it will return what you need, but in the functions (query2) the same error will appear.

Where should I insert it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Protsenko, 2020-04-25
@flawlessattila

$ws_worker->onMessage = function ($connection, $data) use ($db) {
// ...
});

D
Dilce989, 2021-03-28
@Dilce989

I have a question for the author, where did you get this library, rummaged through the entire Internet, even found the page of Workerman itself and the documentation, normal mysql does not allow to implant, pdo made a connection request, entering one message displays it and then simply turns off the server, please share

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question