是什么导致PHP无法连接到我的MySQL数据库? [英] what is preventing PHP from connecting to my MySQL database?
问题描述
[下面更新]
我在使用Bitnami LAMP堆栈连接到MySQL数据库时遇到问题.这是我用来在最初托管数据库的共享主机服务器上连接的代码:
I am having a problem connecting to a MySQL database using a Bitnami LAMP stack. This is the code I used to connect on the shared-hosting server where I originally hosted the database:
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'database');
if ($dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) { // Make the connnection.
if (!mysql_select_db (DB_NAME)) { // If it can't select the database.
// Handle the error.
trigger_error("Could not select the database!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of mysql_select_db IF.
} else { // If it couldn't connect to MySQL.
trigger_error("Could not connect to MySQL!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of $dbc IF.
在我的Bitnami服务器上运行此命令,我没有任何响应(甚至没有错误消息). (PHP运行正常.)
Running this on my Bitnami server, I get no response (not even an error message). (PHP is working fine.)
然后我尝试
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
得到了
Could not connect: Access denied for user 'username'@'localhost' (using password: YES)
此用户名/密码组合确实存在,并且(据我所知)可以访问有问题的数据库.我想知道我在做什么错,为什么原始脚本不会产生错误(或连接).
this username/password combination definitely exists and (as far as I can tell) has access to the database in question. I am wondering what I am doing wrong and why the original script does not produce an error (or connect).
更新:
我遵循了迈克尔在下面的建议,并且能够建立联系.我想重现该问题,因此我删除了该用户,然后通过
I followed Michael's suggestion below, and was able to connect. I wanted to reproduce the issue so I deleted that user then created a user testuser via
CREATE USER 'testuser'@'%' IDENTIFIED BY '***';
GRANT SELECT ,
INSERT ,
UPDATE ,
DELETE ,
FILE ON * . * TO 'testuser'@'%' IDENTIFIED BY '***' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
然后按照迈克尔的建议,我执行了
Then following Michael's suggestion, I executed
GRANT ALL PRIVILEGES ON test . * TO testuser@localhost IDENTIFIED BY 'password'
但是我又得到了
Could not connect: Access denied for user 'testuser'@'localhost' (using password: YES)
(无论我使用'%'还是'localhost',这都行不通)
(This doesn't work whether I use '%' or 'localhost')
这是phpmyadmin中的testuser特权的样子
this is what the privileges look like for testuser in phpmyadmin
Database Privileges Grant Table-specific privileges
test ALL PRIVILEGES No No Edit Privileges
推荐答案
收到的错误消息很清楚-与您连接的用户无法通过您使用的密码进行访问.您需要相应地授予特权:
The error message received is clear - the user you're connecting with does not have access via the password you are using. You'll need to grant privileges accordingly:
GRANT ALL PRIVILEGES on dbname.* to username@localhost IDENTIFIED BY 'thepassword';
这篇关于是什么导致PHP无法连接到我的MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!