Memgraph不支持MySQL协议,PHP 8必须用Bolt客户端(如memgraph/bolt-php)连接,禁用mysqli/PDO;需启用sockets扩展、确认Bolt端口7687连通、使用neo4j/memgraph默认凭据或重置密码,并在ThinkPHP8中通过服务容器或Service类集成异步Bolt调用。

PHP8连接Memgraph数据库时出现“Connection refused”“Authentication failed”或“Unknown authentication method”等错误,本质是Memgraph默认启用的SASL/SCRAM-SHA-256认证机制与PHP 8原生mysqli/pdo_mysql驱动不兼容,且Memgraph不支持传统MySQL协议握手流程。
确认Memgraph服务状态与端口连通性
先排除网络和基础服务问题,避免在配置环节浪费时间。
执行curl -v telnet://127.0.0.1:7687(注意不是3306),观察是否返回Connected to 127.0.0.1。若超时或拒绝连接,说明Memgraph未运行或监听地址非localhost。
检查Memgraph配置文件/etc/memgraph/memgraph.conf中--bolt-server-address=0.0.0.0:7687是否启用,禁用--bolt-server-enabled=false会导致Bolt协议完全关闭。
立即学习“PHP免费学习笔记(深入)”;
【关键前提】Memgraph必须启用Bolt协议,且PHP端必须使用Bolt客户端,不能用mysqli或PDO连接。
安装并配置官方Bolt PHP客户端
Memgraph不兼容MySQL协议栈,必须改用其原生Bolt协议通信。官方推荐memgraph/bolt-php客户端,它基于ReactPHP构建,支持PHP 8.0+。
在项目根目录执行:composer require memgraph/bolt-php。该包会自动拉取react/promise和evenement/evenement依赖。
若报ext-sockets missing,需在PHP中启用sockets扩展:编辑php.ini,取消;extension=sockets前的分号,然后重启PHP-FPM或Apache。
验证扩展是否生效:php -m | grep sockets应输出sockets。
编写可运行的Bolt连接测试脚本
在项目根目录新建test_bolt.php,内容如下:
<?php<br>require_once 'vendor/autoload.php';<br>use Memgraph\Bolt\Client;<br>try {<br> $client = new Client('bolt://127.0.0.1:7687', 'neo4j', 'memgraph');<br> $result = $client->run('RETURN 1 AS n');<br> $record = $result->fetch();<br> echo "Connected successfully: " . $record['n'] . "\n";<br>} catch (Exception $e) {<br> echo "Bolt connection failed: " . $e->getMessage() . "\n";<br>}
注意:默认用户名是neo4j,密码是memgraph——这是Memgraph 2.13+版本的硬编码初始凭据,不是MySQL的root空密码。
执行php test_bolt.php。若输出Connected successfully: 1,说明底层链路已通;若报Invalid credentials,需重置Memgraph密码。
重置Memgraph管理员密码(仅当凭证失效时)
第一步:停止Memgraph服务:sudo systemctl stop memgraph。
第二步:以无认证模式启动临时实例:sudo -u memgraph /usr/lib/memgraph/memgraph --bolt-server-enabled=true --bolt-server-address=127.0.0.1:7687 --auth-enabled=false。
第三步:新开终端,用mgconsole连接:mgconsole -h 127.0.0.1 -p 7687,然后执行:CREATE USER admin SET PASSWORD = 'your_new_pass'; GRANT ALL PRIVILEGES TO admin;。
第四步:退出mgconsole,关闭临时进程,再sudo systemctl start memgraph恢复常规服务。
更新test_bolt.php中的用户名密码为admin和你设置的新密码。
在ThinkPHP8中集成Memgraph Bolt客户端
方法一:注册为全局服务(推荐)
在app/provider/AppServiceProvider.php的register()方法中添加:
$this->app->singleton('memgraph.client', function ($app) {<br> return new \Memgraph\Bolt\Client('bolt://127.0.0.1:7687', 'admin', 'your_new_pass');<br>});
在控制器中通过$this->app->make('memgraph.client')获取实例,无需重复new。
方法二:封装为独立Service类
新建app/service/MemgraphService.php,定义query()和execute()方法,内部调用$this->client->run()并处理Promise返回值。
注意:Bolt客户端所有操作均为异步Promise,不能直接return结果,必须用->done()或await(PHP 8.1+协程环境)消费。



















