Home > database >  Fatal error: Uncaught Error: Class "server\PDO" not found
Fatal error: Uncaught Error: Class "server\PDO" not found

Time:08-13

For a project I'm working on, I am trying to use PHP to connect to a database using PDO. I've stored my data in the .env file for security and have made a class to fetch that data:

.env

DB_SERVER_NAME="localhost",
DB_USER_NAME="root",
DB_PASSWORD="",
DB_NAME="blog"

dbcon.php

<?php

namespace server;

    class env {
        protected $path;

        
        public function __construct(string $path)
        {
            if(!file_exists($path)) {
                throw new \InvalidArgumentException(sprintf('%s does not exist', $path));
            }
            $this->path = $path;
        }

        public function load() :void
        {
            if (!is_readable($this->path)) {
                throw new \RuntimeException(sprintf('%s file is not readable', $this->path));
            }

            $lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {

                if (strpos(trim($line), '#') === 0) {
                    continue;
                }

                list($name, $value) = explode('=', $line, 2);
                $name = trim($name);
                $value = trim($value);

                if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
                    putenv(sprintf('%s=%s', $name, $value));
                    $_ENV[$name] = $value;
                    $_SERVER[$name] = $value;
                }
            }
        }
    }

And then I use that class to connect to the database:

    use server\env;

    (new env(__DIR__ . '/.env'))->load();

    $SERVER_NAME = $_ENV["DB_SERVER_NAME"];
    $USERNAME = $_ENV["DB_USER_NAME"];
    $PASSWORD = $_ENV["DB_PASSWORD"];
    $DBNAME = $_ENV["DB_NAME"];

    try {   
         $data_source = "mysql:host=".$SERVER_NAME.";dbname=".$DBNAME;
         $db = new PDO($data_source, $USERNAME, $PASSWORD);
         print("Connected\n");
     } catch(PDOExeption $ex) {
         die("Could not connect to server");
     }

    $data_source = NULL;

But now I get the error: Fatal error: Uncaught Error: Class "server\PDO" not found I assume it is looking for the PDO class in the server namespace, but I don't know enough about it to understand how to fix this. I could really use your help. Thank you for reading.

CodePudding user response:

Unless you are actually have re-defined standard PDO class, you must use full qualifying name when using all classes.

And since PDO is in global namespaces, you must use it as \PDO:


namespace server;

...

    $db = new \PDO($data_source, $USERNAME, $PASSWORD);

...

Any class usage after namespace declaration assumes you try to load it from same namespace. Exception is when your class has fully qualified name or is used with use statement:


namespace server;

use \Foo\Bar;

...

new Far(); // -> \server\Far - looking in same namespace
new Zar\Far(); // -> \server\Zar\Far - looking in sub-namespace `Zar`
new Bar(); // -> \Foo\Bar - used in `use` statement
new \Zar\Bar(); // -> \Zar\Bar - because of leading \ - full name and not under current namespace
new \Exception(); // -> \Exception - global namespace

CodePudding user response:

The solution is to put the namespace in a separate file and then include that in the dbcon.php file

so the file with the env class would look like this:

<?php
    
    namespace server;

    class env {
        protected $path;

        
        public function __construct(string $path)
        {
            if(!file_exists($path)) {
                throw new \InvalidArgumentException(sprintf('%s does not exist', $path));
            }
            $this->path = $path;
        }

        public function load() :void
        {
            if (!is_readable($this->path)) {
                throw new \RuntimeException(sprintf('%s file is not readable', $this->path));
            }

            $lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {

                if (strpos(trim($line), '#') === 0) {
                    continue;
                }

                list($name, $value) = explode('=', $line, 2);
                $name = trim($name);
                $value = trim($value);

                if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
                    putenv(sprintf('%s=%s', $name, $value));
                    $_ENV[$name] = $value;
                    $_SERVER[$name] = $value;
                }
            }
        }
    }


    use server\env;

    (new env(__DIR__ . '/.env'))->load();

    $SERVER_NAME = $_ENV["DB_SERVER_NAME"];
    $USERNAME = $_ENV["DB_USER_NAME"];
    $PASSWORD = $_ENV["DB_PASSWORD"];
    $DBNAME = $_ENV["DB_NAME"];
?>

And then include it like this:

<?php
    include "fetchenv.php";
    
    try {   
        $data_source = "mysql:host=".$SERVER_NAME.";dbname=".$DBNAME;
        $db = new PDO($data_source, $USERNAME, $PASSWORD);
        print("Connected\n");
    } catch(PDOExeption $ex) {
        die("Could not connect to server");
    }
    
    $data_source = NULL;
?>
  • Related