Querying Polypheny From PHP

Use the Polypheny PHP Driver to run SQL, MongoQL and Cypher from a PHP application. This guide installs the driver, writes and reads relational rows, queries a document collection and traverses a graph. The PHP driver reference covers connection options, transactions, value types and metadata.

Prerequisites

  • 64-bit PHP 8.2 or newer and Composer.
  • A running Polypheny instance with a compatible Prism query interface. The graph example requires the server’s Prism graph implementation and Prism 2.3.
  • A Polypheny account with permission to create, write, read, and drop tables in its default relational namespace for the SQL example.

The examples use Prism TCP at 127.0.0.1:20590. Change the host, port, username, and password to match your instance. The example credentials are for a local setup with the default pa account and an empty password.

Install the driver

Run this command from your PHP project directory. Composer installs version 1.1.0 or a later compatible 1.x release from Packagist and provides vendor/autoload.php for your application.

composer require "polypheny/php-driver:^1.1"

Write and read rows with SQL

Save the following as sql-example.php in your project directory. The script creates a table with a unique name, inserts two rows using positional parameters, and commits the writes. The query binds a named parameter, then iterates through the rows with a fetch size of one. The driver fetches subsequent Prism frames as the loop advances.

<?php

use Polypheny\Connection;

require __DIR__ . '/vendor/autoload.php';

$connection = Connection::connectTcp('127.0.0.1', 20590, 'pa', '');
$table = 'php_integration_fruit_' . bin2hex(random_bytes(4));

try {
    $cursor = $connection->cursor();
    $cursor->execute("CREATE TABLE $table (
        id INTEGER NOT NULL,
        name VARCHAR(50) NOT NULL,
        PRIMARY KEY (id)
    )");

    try {
        $cursor->executeMany("INSERT INTO $table (id, name) VALUES (?, ?)", [
            [1, 'Orange'],
            [2, 'Pear'],
        ]);
        $connection->commit();

        $cursor->execute(
            "SELECT id, name FROM $table WHERE id >= :minimum ORDER BY id",
            ['minimum' => 1],
            fetchSize: 1,
        );
        foreach ($cursor as [$id, $name]) {
            printf("%d: %s\n", $id, $name);
        }
    } finally {
        $connection->rollback();
        $cursor->execute("DROP TABLE $table");
    }
} finally {
    $connection->close();
}
php sql-example.php

The script prints 1: Orange and 2: Pear on separate lines, then drops the example table. Polypheny can commit DDL such as CREATE TABLE automatically, so the script explicitly drops the table during cleanup.

Read a document collection with MongoQL

Save this example as orders.php. It uses an existing document namespace named shop with an orders collection. Adjust the namespace, collection, and filter to match your data. Pass the namespace to executeAny(). Each document comes back as a stdClass.

<?php

use Polypheny\Connection;

require __DIR__ . '/vendor/autoload.php';

$connection = Connection::connectTcp('127.0.0.1', 20590, 'pa', '');

try {
    $cursor = $connection->cursor();
    $cursor->executeAny(
        'mongo',
        'db.orders.find({"status": "open"})',
        fetchSize: 25,
        namespace: 'shop',
    );
    foreach ($cursor as $order) {
        echo json_encode($order, JSON_THROW_ON_ERROR), PHP_EOL;
    }
} finally {
    $connection->close();
}
php orders.php

The script prints one JSON object per matching document. To inspect a collection’s fields and indexes before querying, see the metadata examples in the PHP driver reference.

Traverse a graph with Cypher

Save the example as graph-example.php in the Composer project you set up above. Run it with Polypheny PHP Driver 1.1.0 or later and a server with Prism 2.3 graph support. Use an account that can create and drop graph namespaces and read and write graph data.

The script creates a disposable graph namespace containing Alice, Bob and a KNOWS relationship. It reads the relationship as a flat node-edge-node stream, then returns the node and its name together as a row.

<?php

use Polypheny\Connection;
use Polypheny\Edge;
use Polypheny\Node;

require __DIR__ . '/vendor/autoload.php';

$connection = Connection::connectTcp('127.0.0.1', 20590, 'pa', '');
$namespace = 'php_integration_graph_' . bin2hex(random_bytes(4));

try {
    $cursor = $connection->cursor();
    $cursor->execute("CREATE GRAPH NAMESPACE $namespace");

    try {
        $cursor->executeAny(
            'cypher',
            "CREATE (:Person {name: 'Alice'})-[:KNOWS {since: 2020}]->(:Person {name: 'Bob'})",
            namespace: $namespace,
        );
        $connection->commit();

        $cursor->executeAny(
            'cypher',
            "MATCH (a:Person {name: 'Alice'})-[r:KNOWS]->(b:Person) RETURN a, r, b",
            fetchSize: 1,
            namespace: $namespace,
        );
        foreach ($cursor as $element) {
            if ($element instanceof Node) {
                echo 'Person ', $element->properties['name'], PHP_EOL;
            } elseif ($element instanceof Edge) {
                printf("Relationship %s since %d\n", $element->labels[0], $element->properties['since']);
            }
        }
        $connection->commit();

        $cursor->executeAny(
            'cypher',
            'MATCH (n:Person) RETURN n, n.name AS name ORDER BY name',
            fetchSize: 1,
            namespace: $namespace,
        );
        foreach ($cursor as [$node, $name]) {
            echo $name, ' has node ID ', $node->id, PHP_EOL;
        }
        $connection->commit();
    } finally {
        $connection->rollback();
        $cursor->execute("DROP NAMESPACE $namespace");
    }
} finally {
    $connection->close();
}
php graph-example.php

The first query prints Person Alice, Relationship KNOWS since 2020 and Person Bob. The second prints Alice and Bob with their server-assigned node IDs. Its loop reads the Node and name from the same PHP array. See Cypher and graph results for paths, endpoint IDs and pagination.

© Polypheny GmbH. All Rights Reserved.