emma
emma

Reputation: 759

PDO not found error even tho it is installed and enabled in php.ini

I have a small database class and I'm trying to use PDO to connect to my database but I'm getting this error:

Fatal error: Uncaught Error: Class 'app\lib\PDO' not found in /var/www/html/app/lib/DB.php:11

I checked if PDO is enabled using this code:

if ( extension_loaded('pdo_mysql') ) {
    exit('yes');
}

And the output is "yes".

I've also checked my php.ini and i do have this line (no semi-column):

extension=pdo_mysql

This is my DB.php code:

namespace app\lib;

class DB{

    private static $instance = null;
    public $pdo;

    private function __construct(){
        try {
            $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=db', 'user', 'password');
        } catch (PDOException $e) {
            exit($e->getMessage());
        }
    }

    public static function instance(){

        if(!isset(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }
}

And this is my autoloader(init.php) file:

define('DS', DIRECTORY_SEPARATOR);

spl_autoload_register(function($namespace){
    $path = dirname(__FILE__) . DS . str_replace('\\', DS, $namespace . '.php');

    if(file_exists($path)){
        require_once $path;
    }
});

This is how i am trying to set a new DB connection:

require_once 'init.php';

$db = app\lib\DB::instance(); 

P.S: Pdo works if i don't use namespaces and go for procedural code:

try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=db', 
'user', 'password');
} catch (PDOException $e) {
    exit($e->getMessage());
}

Upvotes: 1

Views: 608

Answers (1)

Dharman
Dharman

Reputation: 33238

Pdo works if i don't use namespaces

This is the key to your solution. PDO is a class in PHP. All class names should be fully qualified, otherwise PHP will look for that class' definition only in the current namespace. To use PDO in any other namespace than global you would need to specify the global namespace with the help of a single \

$this->pdo = new \PDO('mysql:host=127.0.0.1;dbname=db', 'user', 'password');

Side note. The way you are creating the PDO instance is not the recommended one. You should specify the charset as well as enable PDO error reporting.

$this->pdo = new \PDO('mysql:host=127.0.0.1;dbname=db;charset=utf8mb4', 'user', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false,
]);

Never catch exceptions, just to die/exit. Either let the exceptions bubble up, or handle them properly. Displaying the error message to the user manually is a potential security issue.

Upvotes: 1

Related Questions