AsyncMysqlClient::connect
Begin an async connection to a MySQL instance
public static function connect(
string $host,
int $port,
string $dbname,
string $user,
string $password,
int $timeout_micros = -1,
?MySSLContextProvider $ssl_provider = NULL,
): Awaitable<AsyncMysqlConnection>;
Use this to asynchronously connect to a MySQL instance.
Normally you would use this to make one asynchronous connection to the MySQL client.
If you want to be able to pool up a bunch of connections, you would call
setPoolsConnectionLimit()
, create a default pool of connections with
AsyncMysqlConnectionPool()::__construct()
, which now
has that limit set, and then call AsyncMysqlConnectionPool()::connect()
.
Parameters
string $host
- The hostname to connect to.int $port
- The port to connect to.string $dbname
- The initial database to use when connecting.string $user
- The user to connect as.string $password
- The password to connect with.int $timeout_micros = -1
- Timeout, in microseconds, for the connect; -1 for default, 0 for no timeout.?MySSLContextProvider $ssl_provider = NULL
Returns
Awaitable<AsyncMysqlConnection>
- anAwaitable
representing anAsyncMysqlConnection
.await
orjoin
this result to obtain the actual connection.
Examples
The following example shows how to use AsyncMysqlClient::connect()
to connect to a database asynchronously and get a result from that connection. Notice a couple of things:
- The parameters to
connect()
are very similar to that of a normalmysqli
connection. - With
AsyncMysqlClient
, we are able to take full advantage of async to perform other DB connection or I/O operations while waiting for this connection to return.
require __DIR__."/../../__includes/async_mysql_connect.inc.php";
use \Hack\UserDocumentation\API\Examples\AsyncMysql\ConnectionInfo as CI;
async function do_connect(): Awaitable<\AsyncMysqlQueryResult> {
// Cast because the array from get_connection_info() is a mixed
$conn = await \AsyncMysqlClient::connect(
CI::$host,
CI::$port,
CI::$db,
CI::$user,
CI::$passwd,
);
return await $conn->query('SELECT * FROM test_table');
}
function run_it(): void {
$res = \HH\Asio\join(do_connect());
\var_dump($res->numRows()); // The number of rows from the SELECT statement
}
run_it();
int(30)