Documentation Home
Download this Manual
PDF (US Ltr) - 2.5Mb
PDF (A4) - 2.4Mb
HTML Download (TGZ) - 252.2Kb
HTML Download (Zip) - 259.7Kb

MySQL PHP API  /  Mysql_xdevapi  /  Examples

5.3 Examples

Copyright 1997-2020 the PHP Documentation Group.

The central entry point to the X DevAPI is the mysql_xdevapi\getSession function, which receives a URI to a MySQL 8.0 Server and returns a mysql_xdevap\Session object.

Example 5.1 Connecting to a MySQL Server

try {
    $session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
    die("Connection could not be established: " . $e->getMessage());
// ... use $session

The session provides full access to the API. For a new MySQL Server installation, the first step is to create a database schema with a collection to store data:

Example 5.2 Creating a Schema and Collection on the MySQL Server

$schema = $session->createSchema("test");
$collection = $schema->createCollection("example");

When storing data, typically json_encode is used to encode the data into JSON, which can then be stored inside a collection.

The following example stores data into the collection we created earlier, and then retrieve parts of it again.

Example 5.3 Storing and Retrieving Data

$marco = [
  "name" => "Marco",
  "age"  => 19,
  "job"  => "Programmer"
$mike = [
  "name" => "Mike",
  "age"  => 39,
  "job"  => "Manager"

$schema = $session->getSchema("test");
$collection = $schema->getCollection("example");

$collection->add($marco, $mike)->execute();

var_dump($collection->find("name = 'Mike'")->execute()->fetchOne());

The above example will output something similar to:

array(4) {
  string(28) "00005ad66aaf0000000000000003"
  string(7) "Manager"
  string(4) "Mike"

The example demonstrates that the MySQL Server adds an extra field named _id, which serves as primary key to the document.

The example also demonstrates that retrieved data is sorted alphabetically. That specific order comes from the efficient binary storage inside the MySQL server, but it should not be relied upon. Refer to the MySQL JSON datatype documentation for details.

Optionally use PHP's iterators fetch multiple documents:

Example 5.4 Fetching and Iterating Multiple Documents

$result = $collection->find()->execute();
foreach ($result as $doc) {
  echo "${doc["name"]} is a ${doc["job"]}.\n";

The above example will output something similar to:

Marco is a Programmer.
Mike is a Manager.