PHP PDO initialization failed due to "double port" - Uncaught PDOException: SQLSTATE [HY000] [2002]
I am getting this error
PHP Fatal Error: Uncaught PDOException: SQLSTATE [HY000] [2002] Could not parse address "localhost: 3306: 3306" in [myPath] /xxDb.php:32
Note the "dual" port at: localhost: 3306: 3306
xxDb.php line
32 looks like this:
$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
.
I don't see where the second port part comes from 3306
, which obviously exists during connection initialization. Any help is appreciated.
source to share
Showdev's comment is correct that PDO DSN does not allow host: port syntax.
If your CMS defines DB_HOST outside of your control, you cannot use this constant directly. But you can extract information from it.
$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"));
source to share