php mysql_connect: php_network_getaddresses: getaddrinfo 失败: 使用文件值不知道这样的主机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21876269/
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
mysql_connect: php_network_getaddresses: getaddrinfo failed: No such host is known using file values
提问by Jannuzzo
As wrote on the title I have this issue. I have the data that allows me to connect to my database stored in a file. After getting those infos I tried to establish a communication with the database but I receive the warning
正如标题上写的那样,我有这个问题。我有允许我连接到存储在文件中的数据库的数据。获得这些信息后,我尝试与数据库建立通信,但收到警告
Warning: mysql_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\wamp\www\jstool\connect.php on line 21
警告:mysql_connect():php_network_getaddresses:getaddrinfo 失败:不知道这样的主机。在 C:\wamp\www\jstool\connect.php 第 21 行
twice and the result of the connect is nothing even if the values are correct (a.k.a. if I tried the connect writing down the values it works). Here's the txt file:
两次,即使值正确,连接的结果也无济于事(也就是说,如果我尝试连接写下它工作的值)。这是txt文件:
localhost
root
pwd
Here's the code:
这是代码:
ini_set("auto_detect_line_endings", true);
$handle = fopen("config.txt", "r");
if ($handle) {
$i=0;
while (($line = fgets($handle)) !== false) {
$ln[$i]= $line;
$i++;
}
}
define("SERVER", $ln[0]);
define("USER", $ln[1]);
define("PASSWORD", $ln[2]);
$db = mysql_connect(SERVER,USER,PASSWORD);
if (!$db) {
[...]
}
else {
[.. reach database ..]
}
if i simply write
如果我只是写
$db = mysql_connect("localhost", "root", "pwd");
which as you can see are the values contained in the txt file, it works fine.
如您所见,这是 txt 文件中包含的值,它工作正常。
回答by Ian Kenney
try using trim()
尝试使用修剪()
define("SERVER", trim($ln[0]));
define("USER", trim($ln[1]));
define("PASSWORD", trim($ln[2]));
from fgets()manual
来自fgets()手册
Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value)
读取结束时长度 - 1 个字节已被读取,或换行符(包含在返回值中)
so your read includes the newlines.
所以你的阅读包括换行符。

