从PHP连接Memgraph数据库



如何从我的PHP应用程序连接到Memgraph ?它是否类似于我连接MySQL数据库?

部分配置可能看起来类似于您使用PHP和MySQL组合的配置。可能不同的是Composer的用法。您必须安装Composer才能获得所有必需的依赖项。在PHP文件中添加以下代码:

<?php
require_once __DIR__ . '/vendor/autoload.php';
// Create connection class and specify target host and port
$conn = new BoltconnectionSocket();
// Create new Bolt instance and provide connection object
$bolt = new BoltBolt($conn);
// Build and get protocol version instance which creates connection and executes handshake
$protocol = $bolt->build();
// Login to database with credentials
$protocol->hello(BolthelpersAuth::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];

如果您需要支持SSL连接,请使用以下代码:

<?php
require_once __DIR__ . '/vendor/autoload.php';
// Create connection class and specify target host and port
$conn = new BoltconnectionStreamSocket('URI or IP', 7687);
$conn->setSslContextOptions([
'verify_peer' => true
]);
// Create new Bolt instance and provide connection object
$bolt = new BoltBolt($conn);
// Build and get protocol version instance which creates connection and executes handshake
$protocol = $bolt->build();
// Login to database with credentials
$protocol->hello(BolthelpersAuth::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];

现在运行composer:composer require stefanak-michal/bolt

您可以使用php -S localhost:4000运行应用程序

完整的文档可以在Memgraph网站https://memgraph.com/docs/memgraph/connect-to-memgraph/drivers/php上找到。

最新更新