我已经使用 Laravel 一段时间了,但主要是在单个数据库服务器上使用。
现在,我的客户已经从同一网络中的多个数据库服务器获得了至少 5 个数据库。
我能够通过 ssh 使用 ping
并使用
mysqli_connect
检查数据库连接。
但是,当我通过它的 database.php(mysql 配置)使用 laravel 时:
// This setup is working fine (using localhost)
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'dbname',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
// Other DB (which is failing to connect) but i can confrim the connection using a file outside
// the laravel app through mysqli
'other_db_connection' => array(
'driver' => 'mysql',
'host' => '192.168.33.241',
'database' => 'dbname',
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'another_db_connection' => array(
'driver' => 'mysql',
'host' => '192.168.33.211',
'database' => 'dbname',
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
并使用新的PDO
// This connectiion functions with no problem
$conn1 = new PDO('mysql:host=localhost;dbname=dbname;port=3306','username','password');
if($conn1) {
echo 'connected';
}
// But this returns an error
$conn = new PDO('mysql:host=192.168.33.241;dbname=dname;port=3306','username','password');
if($conn) {
echo 'connected';
}
// Also, i have no problems using the DB:: or even the model as long as the host is the localhost
连接失败,PDO 和 laravel 默认数据库功能仅在主机为本地主机时才有效。
出于某种原因,如果我使用其他服务器 ip,它会返回这样的错误,这是我想与之通信的地方:
SQLSTATE[HY000] [2003] 无法连接到“192.168.33.241”上的 MySQL 服务器 (13)
SQLSTATE[HY000] [2003] 无法连接到“192.168.33.211”上的 MySQL 服务器 (13)
当我尝试使用服务器 ip 或主域名进行连接时。
我错过了什么吗?为什么我只能连接到 localhost
的本地数据库服务器
而不是任何其他数据库服务器?但是如果我使用来自 laravel 应用程序外部的 index.php 文件并使用 mysqli_connect 进行查询和建立连接,我可以毫无问题地连接到它们?
感谢您的帮助。
最佳答案
您可以访问您在 database.php 中指定的所有连接:
$user = DB::connection('other_db_connection')
你不需要设置新的 PDO 连接或类似的,会像上面一样为你工作
关于php - Laravel 无法连接到其他数据库服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27550965/