I just set up WAMP server again but I'm hitting a snag. When I try to connect to my database using PHP PDO, I get this error:
SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'ecom'
Here's the code I'm using:
```php
class DBConnector {
private $db_host = 'localhost';
private $db_name = 'shop_db';
private $db_user = 'root';
private $db_pass = '';
public $connection;
public function __construct() {
if (!isset($this->connection)) {
try {
$dsn = "mysql:host={$this->db_host};dbname={$this->db_name}";
$this->connection = new PDO($dsn, $this->db_user, $this->db_pass);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
}
}
Any ideas what might be causing this? I’m stumped!
hey ethan, have u checked if the database name is correct? ur code says ‘shop_db’ but the error mentions ‘ecom’. Maybe thats the issue? also, make sure ur root password is correct. sometimes WAMP sets a default password u might not know about. hope this helps!
Hey Ethan, that error’s a real head-scratcher!
Have you double-checked your MySQL setup in phpMyAdmin? Sometimes WAMP can be finicky with default settings. Also, I’m curious - are you able to connect to any other databases, or is it just this one giving you trouble?
One thing that caught my eye - your code mentions ‘shop_db’, but the error talks about ‘ecom’. Maybe there’s a mix-up there? It might be worth creating a quick test script to print out your database details and see if they match what you’re expecting.
Oh, and here’s a random thought - have you tried restarting WAMP lately? Sometimes that can shake loose weird connection issues. Let us know if you make any progress!
I’ve encountered similar issues before. The error message mentions ‘ecom’, but your code specifies ‘shop_db’. This mismatch could be the root of your problem. Double-check your database name and ensure it’s consistent across your configuration.
Also, verify your MySQL user permissions. Sometimes, even with the correct credentials, the user might lack necessary privileges. You can grant full access to your database with:
GRANT ALL PRIVILEGES ON ecom.* TO ‘root’@‘localhost’;
FLUSH PRIVILEGES;
Run these commands in MySQL as an admin user. If you’re still stuck, check WAMP’s MySQL logs for more detailed error information. They often provide crucial clues for resolving connection issues.