Search code examples
phpmemgraphdb

Connecting to Memgraph database from PHP


How can I connect to Memgraph from my PHP app? Is it similar to the was that I connect MySQL database?


Solution

  • Part of the configuration might look similar to one that you are used to with PHP and MySQL combination. What might be different is the usage of Composer. You have to install Composer to get all of the necessary dependencies. In your PHP file add the following code:

    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    
    // Create connection class and specify target host and port
    $conn = new \Bolt\connection\Socket();
    // Create new Bolt instance and provide connection object
    $bolt = new \Bolt\Bolt($conn);
    // Build and get protocol version instance which creates connection and executes handshake
    $protocol = $bolt->build();
    // Login to database with credentials
    $protocol->hello(\Bolt\helpers\Auth::basic('username', 'password'));
    // Execute query with parameters
    $stats = $protocol->run(
        'CREATE (a:Greeting) SET a.message = $message RETURN id(a) AS nodeId, a.message AS message',
        ['message' => 'Hello, World!']
    );
    // Pull records from last executed query
    $rows = $protocol->pull();
    echo 'Node ' . $rows[0][0] . ' says: ' . $rows[0][1];
    

    In case you need support for SSL connection use the following code:

    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    
    // Create connection class and specify target host and port
    $conn = new \Bolt\connection\StreamSocket('URI or IP', 7687);
    $conn->setSslContextOptions([
    'verify_peer' => true
    ]);
    // Create new Bolt instance and provide connection object
    $bolt = new \Bolt\Bolt($conn);
    // Build and get protocol version instance which creates connection and executes handshake
    $protocol = $bolt->build();
    // Login to database with credentials
    $protocol->hello(\Bolt\helpers\Auth::basic('username', 'password'));
    // Execute query with parameters
    $stats = $protocol->run(
        'CREATE (a:Greeting) SET a.message = $message RETURN id(a) AS nodeId, a.message AS message',
        ['message' => 'Hello, World!']
    );
    // Pull records from last executed query
    $rows = $protocol->pull();
    echo 'Node ' . $rows[0][0] . ' says: ' . $rows[0][1];
    

    Now run the composer: composer require stefanak-michal/bolt.

    You can run the application with php -S localhost:4000

    The complete documentation can be found on the Memgraph web site at https://memgraph.com/docs/memgraph/connect-to-memgraph/drivers/php.