I have been trying to connect to my database through PHP for a few hours now, with no success. My PHP code looks like this:
<?php
ini_set('display_errors', 'On');
$hostname = 'localhost';
$username = 'root';
$password = '';
function testdb_connect($hostname, $username, $password) {
$db = new PDO("mysql:host=$hostname;dbname=asdf", $username, $password);
return $db;
}
try {
$db = testdb_connect($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
What I have already tried:
- Checked if 'root' is configured to 'localhost' (Y)
- Checked if root@localhost has Grant_priv/Super_priv permissions (Y for both)
- Checked if Apache/MySQL is running (Y for both) Checked if my PHP
- Code is wrong, i.e. I am missing something (N)
Any ideas where the Problem could lie? Thanks in advance!
EDIT:
I am so sorry, I have seen the error message so often today, I forgot to mention it here:
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
RE-EDIT:
Here the php code with the user I created:
<?php
ini_set('display_errors', 'On');
$hostname = 'localhost';
$username = 'myUserName';
$password = 'thatUserPassword';
function testdb_connect($hostname, $username, $password) {
$db = new PDO("mysql:host=$hostname;dbname=asdf", $username, $password);
return $db;
}
try {
$db = testdb_connect($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Error Message:
SQLSTATE[HY000] [1045] Access denied for user 'myUserName'@'localhost' (using password: YES)