我有这个简单的代码:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
我收到错误消息:MySQL连接错误:php_network_getaddresses:getaddrinfo失败:所请求的名称有效,但是未找到所请求类型的数据。
我无法弄清楚问题是什么,我一直在谷歌搜索,但是所有建议都失败了(尝试使用127.0.0.1而不是localhost,127.0.0.1:3306等)。
我有与postgre一起使用的代码,但是我需要使用mysql,并且正在尝试对其进行修改,但是我无法通过第一行并获得连接。有什么建议吗?谢谢!
最佳答案
mysql_connect
不使用逗号分隔的字符串。它需要3个单独的字符串。
更改为此:
$dbh = mysql_connect($server, $mysql_user, $password);
如果您绝对有一个用逗号分隔的字符串,并且无法解决此问题,则可以这样分割字符串:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
关于php - 无法在php中连接到MySQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22599404/