Resolving undefined type 'App\PDO' error: Fix when trying to create a PHP CRUD application profile using PDO
P粉235202573
2023-08-31 15:23:03
<p>Entire project - https://github.com/steve-davey/phpsqliteconnect (config file is outdated)</p>
<p>This is the configuration file: </p>
<pre class="brush:php;toolbar:false;"><?php
namespace App;
class Config {
/*** Path to sqlite file*/
const PATH_TO_SQLITE_FILE = 'db/DeviceAssetRegister.db';
}
/* Database credentials. Assume you are running a MySQL server with default settings (user 'root', no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'DeviceAssetRegister');
/* Try to connect to the MySQL database */
try{
$pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
// Set PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("Error: Unable to connect." . $e->getMessage());
}
?></pre>
<p>I don’t understand why there is no error in the index.php file in the above directory, but there is an error for <code>PDO</code>? </p>
<p><code>$pdo = new PDO('sqlite:./db/DeviceAssetRegister.db');</code></p>
<p>That’s totally fine! I even got a little popup description linking to the PHP documentation in VSC. So why are errors reported in other files? Thanks! </p>
PDO
is a class from the root namespace. Unless you are using the root namespace correctly (either by importingPDO
or usingnew \PDO
), PHP will run from the current namespace (i.e.App
) Search for this category.