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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真