使用PDO连接Mysql数据库无法正常工作

use*_*466 7 pdo database-connection

我试图在我的PHP代码中使用PDO模块连接到数据库.我已经阅读并搜索了类似的主题,但我无法弄清楚我做错了什么.请帮我解决这个问题.

  1. Apache版本:Apache/2.2.21(Win32)PHP/5.3.10

  2. 在php.ini文件中,我没有注释掉这行:extension = php_mysql.dll

    2A.phpinfo函数显示'Loaded Configuration File'位置为C:\ php\php.ini

    2B.PDO驱动程序信息由phpinfo函数显示:在PDO部分:PDO驱动程序 - > Mysql(启用)在PDO驱动程序下用于MySQL部分:客户端API版本 - > mysqlnd 5.0.8-dev - 20102224 - $ Revision:321634 $(启用)

我用来连接数据库的代码

$db_user = "uid";
$db_pass = "pd";

$db_connect = new PDO('mysql:host=locahost; dbname=practice; charset=UTF-8', $db_user, $db_pass);
if($db_connect){
    print "connected to the db " . "<br />";
} else{
    print "error connects to the db. " . mysql_error();
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息:

  • 警告:PDO :: __ construct()[pdo .-- construct]:php_network_getaddresses:getaddrinfo failed:没有这样的主机.在第14行的C:\ server\htdocs\html-exer\handle_reg3.php中
  • 警告:PDO :: __ construct()[pdo .-- construct]:[2002] php_network_getaddresses:getaddrinfo failed:没有这样的主机是已知的.(尝试通过tcp:// locahost:3306连接)在第14行的C:\ server\htdocs\html-exer\handle_reg3.php中
  • 致命错误:未捕获异常'PDOException',消息'SQLSTATE [HY000] [2002] php_network_getaddresses:getaddrinfo failed:没有这样的主机已知.'在C:\ server\htdocs\html-exer\handle_reg3.php:14堆栈跟踪:#0 C:\ server\htdocs\html-exer\handle_reg3.php(14):PDO - > __ construct('mysql:host = loca ...','root','password')在第14行的C:\ server\htdocs\html-exer\handle_reg3.php中抛出#1 {main}

编辑:添加了答案,要求提供更多信息,这些信息无疑将很快被删除:

您好常识:感谢代码片段.它帮助我解决了这个问题.看来charset可能是原因.这是我连接到db的代码

$dsn= 'mysql:host=localhost; dbname=practice; charset=utf8';
$db_user = "root";
$db_pass = "mypd";

 $db_connect = new PDO($dsn, $db_user, $db_pass);
 if($db_connect){
     print "connected to the db " . "<br />";
 }
Run Code Online (Sandbox Code Playgroud)

You*_*nse 9

看来你的服务器配置错误只是
使用127.0.0.1的,而不是localhost在DSN.

$dsn = 'mysql:host=127.0.0.1; dbname=practice; charset=utf8';
$pdo = new PDO($dsn, $db_user, $db_pass, $opt);
Run Code Online (Sandbox Code Playgroud)

您需要阅读错误消息.
它说你的PDO连接到localhost有问题.因此,您需要更改PDO连接字符串的地址.

你也使用了错误的字符集名称,我已经纠正了它

此外,mysql_error()与PDO无关.无需调用此函数,您已经抛出错误