简体   繁体   English

PHP MySQL连接失败

[英]PHP MySQL connection failed

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]:无法在第5行的C:\\ xampp \\ htdocs \\ database_connect.php中的'localhost'(10061)上连接到MySQL服务器无法连接:无法连接到'localhost'上的MySQL服务器(10061)

Here are the troubleshooting steps I took: 以下是我采取的故障排除步骤:

  • Checked whether mysqld is running in Windows Task Manager Processes - it is 检查mysqld是否在Windows任务管理器进程中运行 - 它是
  • 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上:连接失败”
  • Checked whether Windows Firewall was blocking MySQL - MySQL is an exception. 检查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的基本有用信息?

You can check that the MySQL server is bound to port 3306 using tcpview . 您可以使用tcpview检查MySQL服务器是否绑定到端口3306。 More simply, drop the port from the host specifier. 更简单地说,从主机说明符中删除端口。 The driver should then attempt to use a named pipe, rather than a TCP socket. 然后,驱动程序应尝试使用命名管道,而不是TCP套接字。

On an unrelated note, I strongly urge you to switch to the PDO MySQL driver. 在一个不相关的说明中,我强烈建议您切换到PDO MySQL驱动程序。 The one you're using is terribly out of date. 你正在使用的是非常过时的。 One big advantage is PDO supports prepared statements , which offer security and efficiency benefits. 一个很大的优点是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,请查看以下建议的资源:

Maybe you don't have remote connections set on the MySQL install. 也许你没有在MySQL安装上设置远程连接。 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已经有一段时间了,但这是一个死的赠品:

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? 你确定它是为端口3306而不是另一个端口配置的吗? Double check that. 仔细检查一下。

The code itself looks fine and is not the issue. 代码本身看起来很好,不是问题。 The port is clearly the issue. 港口显然是个问题。

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 . 最近PHP中的MySQL库(现在使用mysqlnd )的更改在连接到localhost时导致了问题。 A bug has been filled but until then, make sure that your hosts file contains an entry for localhost . 已填写错误,但在此之前,请确保您的hosts文件包含localhost的条目。

Your hosts file localhost entries must look like such: 您的hosts文件localhost条目必须如下所示:

127.0.0.1  localhost
#::1       localhost

As you can see, the IPv6 entry is commented out and the IPv4 entry isn't. 如您所见, IPv6条目已注释掉,而IPv4条目则没有注释掉。

The hosts file is located at: hosts文件位于:

%WINDIR%\System32\drivers\etc\hosts

Source 资源

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

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. 如果'skip_networking'设置为'ON',那么您的MySQL服务器已配置为不允许通过网络访问,并且只能通过本地套接字运行。 Otherwise it'll be listening on the port specified in the 'port' configuration variable. 否则它将监听'port'配置变量中指定的端口。

Ok everybody, here is my very first attempts at connecting MySQL and PHP using PDO as suggested by Outis. 好的大家,这是我第一次尝试使用Outis建议的PDO连接MySQL和PHP。 It worked. 有效。

<?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 ) 数组([exo_flowers_ID] => 1 [0] => 1 [名称] => Dendroseris Neriifolia [1] => Dendroseris Neriifolia [国家] =>智利[2] =>智利[env_workers_id] => 1 [3] = > 1)数组([exo_flowers_ID] => 2 [0] => 2 [名字] => 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'; ?

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已安装,php连接到MySQL无法正常工作):

  1. Open XAMPP Control Panel (my version is v.3.2.1). 打开XAMPP控制面板(我的版本是v.3.2.1)。 Press button "Shell" on the right side of the panel. 按面板右侧的“Shell”按钮。

  2. Window opens with a title: "Administrator: XAMP for Windows – mysql –u root" and with the following text: 窗口打开,标题为:“管理员:XAMP for Windows - mysql -u root”,并带有以下文本:

 Setting environment for using XAMPP for Windows comp@COMP c:\\xampp 
  1. Input: #mysql 输入: #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)

Ie 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”的MySQL连接到MySQL:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM