I am building a login system in php and I am getting an access denied error from my PDO. My credentials are correct so I am not sure what is causing this.
This is the exception
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)'
I've also checked the privileges in phpMyAdmin and everything looks correct.
This is part of my code hopefully someone sees something that I don't...
init.php
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '******',
'db' => '*****'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user'
)
);
spl_autoload_register(function($class){
require_once 'classes/'.$class.'.php';
});
require_once 'functions/sanitize.php';
Config.php
class Config {
public static function get($path = null){
if($path){
$config = $GLOBALS['config'];
$path = explode('/',$path);
foreach($path as $bit){
if(isset($config[$bit])){
$config = $config[$bit];
}
}
return $config;
}
return false;
}
}
Part of my DB.php
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname=' . Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
echo 'Connected!';
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
Index.php
require_once 'core/init.php';
$user = DB::getInstance();
Your static method on config is not iterating over the structure. You are providing array('mysql/username') as the path, it gets broken down to 'mysql' and 'username' for the foreach and the isset($config['mysql']) returns true and then $config is set to an array (with everything from 'mysql' key) and then you return the array and not the value you want.
foreach($path as $bit){
if(isset($config[$bit])){
$config = $config[$bit]; // <-- returns $config['mysql']
}
}