PHP MySQL 连接失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2218877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:35:00  来源:igfitidea点击:

PHP MySQL connection failed

phpmysql

提问by Anthony

I am trying to connect my PHP code to MySQL safely with the following code:

我正在尝试使用以下代码将我的 PHP 代码安全地连接到 MySQL:

<html>
    <?php
        $con = mysql_connect("localhost:3306","root","password");
        if(!$con)
        {
            die('Could not connect: ' . mysql_error());
        }
        else
        {
            echo "Connection established!";
        }
        mysql_close($con);
    ?>
</html>

But I keep getting the following error message:

但我不断收到以下错误消息:

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'localhost' (10061) in C:\xampp\htdocs\database_connect.php on line 5 Could not connect: Can't connect to MySQL server on 'localhost' (10061)

警告:mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'localhost' (10061) in C:\xampp\htdocs\database_connect.php on line 5 无法连接:无法连接“本地主机”上的 MySQL 服务器 (10061)

Here are the troubleshooting steps I took:

以下是我采取的故障排除步骤:

  • Checked whether mysqld is running in Windows Task Manager Processes - it is
  • Checked whether MySQL was running on the host by typing in Windows command prompt: "telnet 192.0.0.1 3306" and got the message "Could not open connection to the host, on port 3306: connection failed"
  • Checked whether Windows Firewall was blocking MySQL - MySQL is an exception.
  • 检查 mysqld 是否在 Windows 任务管理器进程中运行 - 它是
  • 通过在 Windows 命令提示符下键入:“telnet 192.0.0.1 3306”检查 MySQL 是否在主机上运行,​​并收到消息“无法打开与主机的连接,在端口 3306:连接失败”
  • 检查 Windows 防火墙是否阻止 MySQL - MySQL 是一个例外。

How do I get this code to work safely? And how do I check basic useful information about my MySQL like username?

如何让此代码安全地工作?以及如何检查有关我的 MySQL 的基本有用信息,例如用户名?

回答by outis

You can check that the MySQL server is bound to port 3306 using tcpview. More simply, drop the port from the host specifier. The driver should then attempt to use a named pipe, rather than a TCP socket.

您可以使用tcpview检查 MySQL 服务器是否绑定到端口 3306 。更简单地说,从主机说明符中删除端口。然后驱动程序应该尝试使用命名管道,而不是 TCP 套接字。

On an unrelated note, I strongly urge you to switch to the PDOMySQL driver. The one you're using is terribly out of date. One big advantage is PDO supports prepared statements, which offer security and efficiency benefits.

在一个不相关的说明中,我强烈建议您切换到PDOMySQL 驱动程序。你正在使用的那个已经过时了。一大优势是 PDO 支持准备好的语句,这提供了安全性和效率优势。

Edit:

编辑:

This doesn't answer your main question, but posting this information in a comment would be a mess.

这不能回答您的主要问题,但在评论中发布此信息会一团糟。

Rather than W3Schools, check out the resources suggested in:

请查看以下建议的资源,而不是 W3Schools:

回答by mr-sk

Maybe you don't have remote connections set on the MySQL install. You're attempting to connect over a port, which is the same as a remote connection. It's been a while since I've done MySQL, but this is a dead giveaway:

也许您没有在 MySQL 安装上设置远程连接。您正在尝试通过端口进行连接,这与远程连接相同。我已经有一段时间没有完成 MySQL 了,但这是一个致命的赠品:

Checked whether MySQL was running on the host by typing in Windows command prompt: "telnet 192.0.0.1 3306" and got the message "Could not open connection to the host, on port 3306: connection failed"

通过在 Windows 命令提示符下键入:“telnet 192.0.0.1 3306”检查 MySQL 是否在主机上运行,​​并收到消息“无法打开与主机的连接,在端口 3306:连接失败”

It's not going to work. Are you sure it's configured for port 3306 and not another port? Double check that.

这是行不通的。你确定它是为端口 3306 而不是另一个端口配置的吗?仔细检查一下。

The code itself looks fine and is not the issue. The port is clearly the issue.

代码本身看起来不错,不是问题。端口显然是问题所在。

回答by Andrew Moore

Note:This is not the solution to the OP's problem, but I will keep my answer for historical reasons and also because it might be the issue for some other folks.

注意:这不是 OP 问题的解决方案,但出于历史原因,也因为它可能是其他一些人的问题,我会保留我的答案。

Are you on Windows Vista/7 and running PHP 5.3.1?

您使用的是 Windows Vista/7 并运行 PHP 5.3.1 吗?

A recent change in the MySQL library in PHP right now (now using mysqlnd) is causing problems when connecting to localhost. A bug has been filled but until then, make sure that your hostsfile contains an entry for localhost.

PHP 中 MySQL 库的最近更改(现在使用mysqlnd)在连接到localhost. 一个错误已被填补,但在那之前,请确保您的hosts文件包含localhost.

Your hostsfile localhostentries must look like such:

您的hosts文件localhost条目必须如下所示:

127.0.0.1  localhost
#::1       localhost

As you can see, the IPv6entry is commented out and the IPv4entry isn't.

如您所见,该IPv6条目已被注释掉,而该IPv4条目未被注释掉。

The hostsfile is located at:

hosts文件位于:

%WINDIR%\System32\drivers\etc\hosts

Source

来源

回答by useless

You can't recover the password, but you can create a new one. Turn off the MySQL service and execute:

您无法恢复密码,但可以创建一个新密码。关闭MySQL服务,执行:

cd c:\mypathtomysql\bin
mysqladmin -u root password NEWPASSWORD

回答by Marc B

If you can access the MySQL shell, you can check the server's networking configuration like this:

如果您可以访问 MySQL shell,您可以像这样检查服务器的网络配置:

mysql> show variable like 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  | 
+---------------+-------+
mysql> show variables like 'skip_networking';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| skip_networking | OFF   | 
+-----------------+-------+
1 row in set (0.00 sec)

If 'skip_networking' is set to 'ON', then your MySQL server has been configured to NOT allow access via the network and will function only via local sockets. Otherwise it'll be listening on the port specified in the 'port' configuration variable.

如果“skip_networking”设置为“ON”,则您的 MySQL 服务器已配置为不允许通过网络访问,并且只能通过本地套接字运行。否则,它将侦听 'port' 配置变量中指定的端口。

回答by Anthony

Ok everybody, here is my very first attempts at connecting MySQL and PHP using PDO as suggested by Outis. It worked.

大家好,这是我第一次尝试按照 Outis 的建议使用 PDO 连接 MySQL 和 PHP。有效。

<?php 
$user = root;
$pass = password;
try
{
    $dbh = new PDO('mysql:host = localhost; dbname=databaseName', $user,$pass);
    if($dbh)
    {
        print "Connected successfully";
    }
}
catch (PDOException $e)
{
    print "Error: " . $e->getMessage(). "<br/>";
    die();
}
?>

Here is my second attempt - this time I am trying to do a query

这是我的第二次尝试 - 这次我正在尝试进行查询

<?php 
$user = root;
$pass = password;
try
{
    $dbh = new PDO('mysql:host = localhost; dbname=databaseName', $user,$pass);
    foreach($dbh->query('SELECT * FROM tableName') as $row)
{
    print_r($row);
}
$dbh = null; 
}
catch (PDOException $e)
{
    print "Error: " . $e->getMessage(). "<br/>";
    die();
}
?>

After running this code, I get the following results:

运行此代码后,我得到以下结果:

Array ( [exo_flowers_ID] => 1 [0] => 1 [name] => Dendroseris Neriifolia [1] => Dendroseris Neriifolia [country] => Chile [2] => Chile [env_workers_id] => 1 [3] => 1 ) Array ( [exo_flowers_ID] => 2 [0] => 2 [name] => Snowdonia Hawkweed [1] => Snowdonia Hawkweed [country] => North Wales [2] => North Wales [env_workers_id] => 1 [3] => 1 )

Array ( [exo_flowers_ID] => 1 [0] => 1 [name] => Dendroseris Neriifolia [1] => Dendroseris Neriifolia [国家] => 智利 [2] => 智利 [env_workers_id] => 1 [3] = > 1 ) Array ( [exo_flowers_ID] => 2 [0] => 2 [name] => Snowdonia Hawkweed [1] => Snowdonia Hawkweed [country] => 北威尔士 [2] => 北威尔士 [env_workers_id] => 1 [3] => 1 )

All I wanted was to display the contents of a row or column , but instead I got all of the contents plus all these brackets. How do I display only the contents of a table's row or column?

我想要的只是显示行或列的内容,但我得到了所有内容加上所有这些括号。如何仅显示表格行或列的内容?

And finally, how do I so a query like: SELECT * FROM tableName WHERE 'columnName1' = 'somename' AND 'columnName2' = 'someothername'; ?

最后,我如何进行这样的查询: SELECT * FROM tableName WHERE 'columnName1' = 'somename' AND 'columnName2' = 'someothername'; ?

回答by Elia12345

I solved the same problem "Can't connect to MySQL server on 'localhost'" with the following steps (Windows 7, XAMPP v.3.2.1 installed, php connection to MySQL didn't work):

我通过以下步骤解决了同样的问题“无法连接到 'localhost' 上的 MySQL 服务器”(Windows 7,安装了 XAMPP v.3.2.1,到 MySQL 的 php 连接不起作用):

  1. Open XAMPP Control Panel (my version is v.3.2.1). Press button "Shell" on the right side of the panel.

  2. Window opens with a title: "Administrator: XAMP for Windows – mysql –u root" and with the following text:

  1. 打开 XAMPP 控制面板(我的版本是 v.3.2.1)。按下面板右侧的“外壳”按钮。

  2. 窗口打开,标题为:“管理员:XAMP for Windows – mysql –u root”和以下文本:

Setting environment for using XAMPP for Windows
comp@COMP c:\xampp
Setting environment for using XAMPP for Windows
comp@COMP c:\xampp
  1. Input: #mysql
  1. 输入: #mysql

Obtained answer: Welcome to the MySQL monitor…

得到答案: Welcome to the MySQL monitor…

Then input: mysql>create database mdb;

然后输入: mysql>create database mdb;

Answer: ERROR 1044 (42000): Access denied for user ‘'@'localhost' to database ‘drawdb'

回答: ERROR 1044 (42000): Access denied for user ‘'@'localhost' to database ‘drawdb'

Input: #mysql –u root

输入: #mysql –u root

Answer: Welcome to the MySQL monitor…

回答: Welcome to the MySQL monitor…

Input: mysql>create database mdb;

输入: mysql>create database mdb;

Answer: Query OK, 1 row affected (0.00 sec)

回答: Query OK, 1 row affected (0.00 sec)

Input: mysql>grant all on mdb.* to user@localhost identified by ‘password';

输入: mysql>grant all on mdb.* to user@localhost identified by ‘password';

Answer: Query OK, 0 rows affected (0.06 sec)

回答: Query OK, 0 rows affected (0.06 sec)

I.e. I allowed access to the manually created database to the specified user. After that php connection to MySQL with user “user” and password “password” could be successfully created:

即我允许指定用户访问手动创建的数据库。之后,可以成功创建用户“user”和密码“password”的 php 连接到 MySQL:

> $servername = "localhost";  
> $username = "user";  
> $password = "password"; 
> // Create connection 
> $conn = new mysqli($servername, $username, $password);