简体   繁体   English

通过PHP访问远程数据库MySQL

[英]Access remote database MySQL via PHP

I have a MySQL database set up on 000webhost.com. 我在000webhost.com上设置了一个MySQL数据库。 I want to access the data in my database via PHP. 我想通过PHP访问我的数据库中的数据。 I tried: 我试过了:

<?php 

include("connect.php");
mysql_select_db("XXXXXXX_users", $con) or die(mysql_error()); 

$result = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row = mysql_fetch_array($result))     
{
    $id = $row['id'];
    $user = $row['usrname'];
} 


echo "$user";
?>

But it always returns as: "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." 但它总是返回:“连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应。”

What do I do? 我该怎么办?

  • I do not have root access 我没有root访问权限
  • I'm trying to run the script on Apache 我正在尝试在Apache上运行脚本

When debugging this sort of thing, it's always good to make sure you can connect using the command line mysql tool first, to rule out issues related to PHP itself. 在调试此类事情时,最好先确保可以使用命令行mysql工具进行连接,以排除与PHP本身相关的问题。

$ mysql -u myuser -h mysql.example.com -p

You'll get a more descriptive error message as well, eg ERROR 1045 (28000): Access denied for user 'root'@'remote.example.com' (using password: YES) 您还会收到更具描述性的错误消息,例如ERROR 1045 (28000): Access denied for user 'root'@'remote.example.com' (using password: YES)

If the mysql port is even open on a public interface to begin with (which is usually a terrible idea), mysql itself has its own layer of access control based on the connecting host. 如果mysql端口甚至在公共接口上打开(这通常是一个可怕的想法),mysql本身就有自己的访问控制层,基于连接主机。 You may need to have an account created specifically with a wildcard hostname, like so: 您可能需要使用通配符主机名创建一个帐户,如下所示:

CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypassword';

The @'%' part, specifically, allows connection from any host, local or remote. 具体来说, @'%'部分允许从任何主机,本地或远程连接。

Once you can successfully connect from the command line, it's then a simple issue of replicating your command line arguments as arguments to mysql_connect() 一旦您可以从命令行成功连接,那么将命令行参数复制为mysql_connect()参数就是一个简单的问题。

A lot(if not all?) of hosting providers restrict remote access to the mysql database. 很多(如果不是全部?)托管服务提供商限制远程访问mysql数据库。 Meaning that you can only connect via localhost. 这意味着您只能通过localhost连接。 There is probably a mysql config section on the hosting provider that will allow you to config an ip address from which a certain user can connect from. 托管服务提供商上可能有一个mysql配置部分,允许您配置某个用户可以从中连接的IP地址。 Good luck. 祝好运。

大多数主机不提供远程访问MySQL服务器,因为它存在安全风险,您是否可以尝试另一个允许远程访问的免费MySQL服务器,试试这个但是它有点慢。

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

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