[英]PHP mysqli connection to remote database
Trying to connect to a database that is not on the same host as my site for the first time and not having much luck. 第一次尝试连接到与我的站点不在同一主机上的数据库,但运气不佳。 The DB is on a godaddy host and I have configured it to allow remote access: 该数据库位于godaddy主机上,我已将其配置为允许远程访问:
$dbc = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$dbc) {
die('Connect Error: ' . mysqli_connect_error());
}
and I get the following on page: 我在页面上看到以下内容:
Warning: mysqli_connect() [function.mysqli-connect]: [2002] Connection timed out (trying to connect via 'mydbhostname:3306) in 'path' on line 3 警告:mysqli_connect()[function.mysqli-connect]:[2002]连接超时(尝试通过第3行上的“路径”中的“ mydbhostname:3306连接”)
Warning: mysqli_connect() [function.mysqli-connect]: (HY000/2002): Connection timed out in 'path' on line 3 警告:mysqli_connect()[function.mysqli-connect]:(HY000 / 2002):连接在第3行的'path'中超时
Connect Error: Connection timed out 连接错误:连接超时
Anything I need to look for on my end or something in the script that could be causing this? 我需要在终端上寻找什么,还是脚本中可能导致这种情况的任何东西?
EDIT: well it appears everything works when I use mysql, but not mysqli...and mysqli is enabled on the server. 编辑:好吧,当我使用mysql而不是mysqli时,似乎一切正常,并且在服务器上启用了mysqli。
I had the same problem on a Digitalocean Ubuntu 14.04 server, where the firewall configuration was the culprit. 我在Digitalocean Ubuntu 14.04服务器上遇到了同样的问题,其中防火墙配置是罪魁祸首。 Mysql wasn't allowed on port 3306 by the ufw firewall rules. ufw防火墙规则不允许在端口3306上使用Mysql。
Solution: 解:
$ sudo ufw status
$ sudo ufw allow mysql
$ sudo ufw reload
Make sure that you have inserted correct hostname for your database, here you can see how to do it on godaddy hosting: 确保为数据库插入了正确的主机名,在这里您可以查看如何在godaddy主机上执行此操作:
I don't understand the difference between mysqli and mysql, but I've found on GoDaddy that using: 我不了解mysqli和mysql之间的区别,但是我在GoDaddy上发现使用:
mysqli_connect doesn't work. mysqli_connect不起作用。 mysql_connect does work. mysql_connect确实起作用。
Try using the following sample code to see if you can connect to your database which needs data in at least one table: 尝试使用以下示例代码来查看是否可以连接到至少需要一个表中的数据的数据库:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "XXXXXXX.db.XXXXXXXX.hostedresource.com";
$username = "XXXXXXX";
$dbname = "XXXXXXX";
//These variable values need to be changed by you before deploying
$password = "XXXXXXX";
$usertable = "XXXXXXX";
$yourfield = "XXXXXXX";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$yourfield"];
echo "<h2>some data</h2>";
echo "$name<br>";
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.