PHP PDO初始化失败,因为“双端口”-未捕获的PDOException: SQLSTATE[HY000] [2002]

时间:2022-10-14 14:03:48

I get this error

我得到这个错误

PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Failed to parse address "localhost:3306:3306" in [myPath]/xxDb.php:32

PHP致命错误:未捕获的PDOException: SQLSTATE[HY000][2002]未能解析[myPath]/xxDb.php:32中的“localhost:3306:3306”地址

Notice the "double" port in the address: localhost:3306:3306

注意地址:localhost:3306:3306中的“double”端口

xxDb.php line 32 looks like this:

xxDb。php第32行如下:

$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8', DB_USER, DB_PW, array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" ));

dumping DB_HOST results in localhost:3306.

DB_HOST导致localhost:3306。

I can not see where the second port part 3306 comes from which obviously exists during the connection initialization. Any help is highly appreciated.

我看不出第二个端口3306来自哪里,在连接初始化过程中,它显然存在。非常感谢您的帮助。

1 个解决方案

#1


2  

showdev's comment is correct that the PDO DSN does not allow host:port syntax.

showdev的评论是正确的,PDO DSN不允许主机:端口语法。

If your CMS is defining DB_HOST outside of your control, you can't use that constant directly. But you can pull information out of it.

如果CMS在控件之外定义DB_HOST,则不能直接使用该常量。但是你可以从中提取信息。

$host_port = preg_replace('/:(\d+)/', ';port=${1}', DB_HOST);
$db = new PDO("mysql:host={$host_port};dbname=".DB_NAME.";charset=utf8", 
    DB_USER, DB_PW, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

#1


2  

showdev's comment is correct that the PDO DSN does not allow host:port syntax.

showdev的评论是正确的,PDO DSN不允许主机:端口语法。

If your CMS is defining DB_HOST outside of your control, you can't use that constant directly. But you can pull information out of it.

如果CMS在控件之外定义DB_HOST,则不能直接使用该常量。但是你可以从中提取信息。

$host_port = preg_replace('/:(\d+)/', ';port=${1}', DB_HOST);
$db = new PDO("mysql:host={$host_port};dbname=".DB_NAME.";charset=utf8", 
    DB_USER, DB_PW, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));