AsyncMysqlClient::connect

Begin an async connection to a MySQL instance

Description

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

  • $host - The hostname to connect to.
  • $port - The port to connect to.
  • $dbname - The initial database to use when connecting.
  • $user - The user to connect as.
  • $password - The password to connect with.
  • $timeout_micros = -1 - Timeout, in microseconds, for the connect; -1 for default, 0 for no timeout.
  • ?MySSLContextProvider $ssl_provider = null

Return Values

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 normal mysqli 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.
<?hh

namespace Hack\UserDocumentation\API\Examples\AsyncMysql\Client\Conn;

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();
Output
int(30)