Windows下安装了一套WampServer环境开发PHP程序,写了一段超级简单的程序进行数据库链接:
try { $dbh = new PDO("mysql:host=localhost;dbname=todolist", "root", 'root'); //初始化一个PDO对象 echo "连接成功"; $dbh = null; } catch (PDOException $e) { die ("Error!: " . $e->getMessage()); }
在公司的环境下一点问题都没有,同样的方式进行配制的环境,在家里的电脑死活就不行,一执行就报错:
Error!: SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: YES)
我确定用户名和密码都没有写错,但还是按照通常的解决方法试了一遍,还是不行:
In MySQL, a user is identified by both a username (test2) and a host (localhost).
The error message you are getting identify the user (test2) and host (localhost) values…
'test2'@'localhost'
Check to see if that user exists, using this query from a client you can connect from:
SELECT user, host FROM mysql.user
You’re looking for a row that has test2 for user, and localhost for host.
user host ------- ----------- test2 127.0.0.1 test2 ::1 test2 localhost
If that row doesn’t exist, then the host may be set to wildcard value of %, to match any other host that isn’t a match.
If the row exists, then the password may not match. You can change the password (if you’re connected as a user with sufficient privileges, e.g. root
SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')
Also verify that the user has privileges on objects in the database.
GRANT SELECT ON jobs.* TO 'test2'@'localhost'
重新安装了一次WampServer,甚至还参考MySQL官方论坛寻找解决方案 https://forums.mysql.com/read.php?11,661415,661415 ,还是不行。
后面直接看起了MySQL的配制文件my.ini,看到端口号(port)的配制,想到可能是因为没有加端口号。然后把端口号加上试了一下。果然可以:
$dbh = new PDO("mysql:host=localhost:3307;dbname=todolist", "root", 'root'); //初始化一个PDO对象
就这么一个小失误,查问题查的跳楼的心都有了。现在大概明白原因了,WampServer是一个集成多个软件的一整套的开发环境,安装成功后会同时安装MySQL和MariaDB这两个数据库。MySQL默认的端口号是3306,而MariaDB默认的端口号是3307,可以查看他们的配制文件。而我使用的是MariaDB数据库,但PHP数据库链接时,没有加端口可能会使用默认的端口号3306,所以导致失败。
MySQL和MariaDB的区别和关系可参考: http://blog.csdn.net/liumiaocn/article/details/56665800
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。