Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to create PHP CRUD app using PDO but getting Undefined type 'App\PDO' in config file

Entire project – https://github.com/steve-davey/phpsqliteconnect (config file is out of date though)

This is the config file:

<?php

namespace App;

class Config {
   /**
    * path to the sqlite file
    */
    const PATH_TO_SQLITE_FILE = 'db/DeviceAssetRegister.db';

}

/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'DeviceAssetRegister');
 
/* Attempt to connect to MySQL database */
try{
    $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
?>

I don’t understand why I get an error for PDO whereas I don’t for the index.php file in the directory above?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$pdo = new PDO('sqlite:./db/DeviceAssetRegister.db');

That works absolutely fine! I even get a little pop-up description in VSC that links to the PHP documentation. So why does it throw an error in the other file please?? TIA!

>Solution :

PDO is a class from the root namespace. Unless you use that root namespace properly (by either importing PDO or using new \PDO), PHP will search that class from the current namespace (which is App)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading