使用PHP连接远程MySQL服务器

11

我正尝试使用以下代码从我的本地机器虚拟主机连接到远程MySQL服务器:

$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass") or die(mysql_error());
        mysql_select_db($dbname, $conn) or die(mysql_error());

我的问题是我无法在本地连接,收到以下错误信息:

无法连接到MySQL服务器 'xxx.xxx.xxx.xxx' (10060)

当我将相同的PHP文件上传到服务器时,情况并非如此。我可以毫无问题地查询数据库。

我也无法通过命令行连接,但我可以访问cPanel,这排除了我的IP被意外禁止的可能性。

我的本地服务器运行的是PHP 5.2.9,远程服务器运行的是5.2.12。

4个回答

18
  • 服务器的防火墙必须设置为允许在3306端口上接收传入连接
  • 您必须在MySQL中拥有一个允许从 % (任何主机) 连接的用户(详情请参阅手册)

当前问题是第一个,但在解决第一个问题后,您可能会遇到第二个问题。


当问题首次出现时,我在远程MySQL中创建了一个通配符用户,以为我的IP可能已经改变(尽管不应该改变)。几天前我还能连接到同一台服务器,所以我怀疑这不是防火墙的问题。 - BenTheDesigner
3
尝试使用 Telnet 命令连接到 xx.xx.xx.xx 的 3306 端口。如果连接不成功,则可能存在网络问题。 - Bozho
@Bozho:无法 Telnet 到 3306 端口。由于这是共享服务器,我必须与主机联系,因为我无法访问他们的网络。 - BenTheDesigner
是的,是这样的。也向主机管理员询问一下。 - Bozho
@Jacob:MySQL可以使用其配置的任何端口,尽管在这种情况下它正在运行3306端口 - 上周我能够连接到它,只是出现了某些原因导致它挂掉了。 - BenTheDesigner
显示剩余3条评论

3
很容易通过PHP连接远程MySQL服务器,你需要做的是:
  1. 在远程服务器上创建一个MySQL用户。

  2. 为该用户授予完全权限。

  3. 使用PHP代码连接到服务器(以下是示例)。

请注意:文本中保留了HTML标签。
$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306

2

我刚刚解决了这种问题。 我学到的是:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

现在,您应该能够从客户端服务器的 PHP 脚本连接到 MySQL 服务器。


1
这可能不是对发帖者问题的答案。但这可能有助于那些面临与我相同情况的人:

客户端有两个网络适配器,一个无线和一个普通的。可以成功ping到服务器。然而,telnet serverAddress 3306会失败,并且会出现以下错误提示:
无法连接到MySQL服务器'xxx.xxx.xxx.xxx'(10060)

尝试连接服务器时。所以我禁用了普通网络适配器。并尝试使用telnet serverAddress 3306,它有效。然后连接到MySQL服务器也有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接