[Updated below]
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
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
MySQL Error: " . mysql_error());
exit();
} // End of $dbc IF.
Running this on my Bitnami server, I get no response (not even an error message). (PHP is working fine.)
I then tried
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
and got
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).
Update:
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'
but again I am getting
Could not connect: Access denied for user 'testuser'@'localhost' (using password: YES)
(This doesn't work whether I use '%' or 'localhost')
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';