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

Viewed 27

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?

$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!

1 Answers

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)

Related