gpt4 book ai didi

PHP PDO : SQLSTATE[HY000] [2002] Connection refused

转载 作者:行者123 更新时间:2023-11-29 02:11:49 24 4
gpt4 key购买 nike

我在使用 PHP 数据对象时遇到了这个问题。

我无法连接到我的数据库。首先是我的 PHP 脚本:

<?php

$serverName = "127.0.0.1";
$port = "3306";
$dbName = "callitTime";
$userName = "root";
$password = "superstrongPassword";

try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName;port=$port;",
$userName, $password);

} catch (PDOException $pdoE) {
echo 'An Error occurred: ' . $pdoE->getMessage();
}
?>

我正在使用:

  • PHP 7.1.16

  • Nginx 1.13.12-1

  • MySQL 8.0.11-1debian9

全部作为 Docker 容器。

phpinfo() 告诉我 PDO 驱动程序加载如下:

PDO 驱动程序:

  • sqlite

  • mysql

驱动程序版本:

  • mysqlnd 5.0.12-dev

  • SQLite 库 3.15.1

我得到错误:

An Error occurred: SQLSTATE[HY000] [2002] Connection refused

我可以使用相同的密码和用户名通过 Phpstorm 连接到相同的数据库。

最佳答案

这似乎不是与 PHP 配置相关的问题。

错误 Connection refused 从我的角度来看,您无法建立从 php 容器到 mysql 容器的连接。

需要将3306端口暴露给Webserver Container,这样PHP Container才能与数据库建立连接。如果您已经桥接容器,则需要使用容器 IP 地址,而不是环回 127.0.0.1。

Please see this answer for more information how to connect both containers and how to make a connection from a php to a mysql container:
https://stackoverflow.com/a/43128428/1118905

要缩小问题范围,您可以尝试通过 Netcat 从 PHP 容器内建立连接到给定的数据库主机。

例如,您可以尝试使用以下命令建立连接:

  1. Get into the container from which you want to test the connection.
    docker exec -it <name_of_container> bash
  2. Test to open up a connection via netcat (If not all ready available install it via f.e. apt)
    nc -vz 127.0.0.1:3306

关于PHP PDO : SQLSTATE[HY000] [2002] Connection refused,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com