dongyi1429 2014-03-24 01:04
浏览 22
已采纳

无法在php中获得与MySQL的连接

I have this simple code:

<?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());
}
...

And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.

I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)

I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!

  • 写回答

4条回答 默认 最新

  • douyao2529 2014-03-24 01:06
    关注

    mysql_connect doesn't take a comma seperated string. It takes 3 individual strings. Change it to this:

    $dbh = mysql_connect($server, $mysql_user, $password);
    

    If you absolutely have a comma separated string, and can't get around this, you can split the string like this:

     $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());
         }
     } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题