dongyi1429 2014-03-23 17: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-23 17: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条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥45 字符串操作——数组越界问题
  • ¥15 Loss下降到0.08时不在下降调整学习率也没用
  • ¥30 怎么把PCK、OKS指标添加到yolov11中
  • ¥15 QT+FFmpeg使用GPU加速解码
  • ¥15 为什么投影机用酷喵播放电影放一段时间就播放不下去了?提示发生未知故障,有什么解决办法吗?
  • ¥15 来个会搭建付费网站的有偿
  • ¥100 有能够实现人机模式的c/c++代码,有图片背景等,能够直接进行游戏
  • ¥20 校园网认证openwrt插件
  • ¥15 以AT89C51单片机芯片为核心来制作一个简易计算器,外部由4*4矩阵键盘和一个LCD1602字符型液晶显示屏构成,内部由一块AT89C51单片机构成,通过软件编程可实现简单加减乘除。
  • ¥15 求GCMS辅导数据分析
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部