简体   繁体   English

无法使用PDO连接到数据库

[英]Unable to connect to database using PDO

I am new in PHP programming trying to connect to database using PDO. 我是PHP编程的新手,试图使用PDO连接到数据库。 But while doing getting error as: 但是在出现以下错误时:

"Class 'DB' not found in D:\\xampp\\htdocs\\web\\oop\\index.php on line 5" “在第5行的D:\\ xampp \\ htdocs \\ web \\ oop \\ index.php中找不到类'DB'”

please help." details are given blow. thanks in advance. 请帮助。”细节一击而过。在此先感谢。

config.php config.php

    <?php
    class Config{
     public static function get($path = null)
    {
    if($path){
        $config = $GLOBALS['config'];
        $path = explode('/', $path);

        foreach($path as $bit)
        {
            if(isset($config[$bit]))
            {
                $config = $config[$bit];
            }
        }
        return $config;
     }
          } 
        }
      ?>

core/init.php 核心/ init.php

     require_once 'functions/sanitize.php';

     $GLOBALS['config'] = array(
    'mysql' => array(
    'host'=> '127.0.0.1',
    'username' => 'root',
    'password' => '',
    'db' => 'oop'
    ),
'remember' => array(
    'cookie_name' => 'hash',
    'cookie_expiry' => 604800
    ),
'session' => array(
    'session_name' => 'user'
    )
  );


    spl_autoload_register(function($class)
   {

require_once 'classes/' . $class . '.php';
 }
    )


 ?>

classes/DB.php 类/DB.php

     <?php
    namespace application\libs;
    use POD;
    class DB
    {

        private static $_instance = null;
        private $_pdo,
                $_query,
                $_error = false,
                $_results,
                $_count = 0;


        private function __construct()
        {
            try{
                $this->_pdo = new POD('mysql:host=' .
                Config::get('mysql/host') . ';dbname=' .
                 Config::get('mysql/db'), Config::get('mysql/username'),
                     Config::get('mysql/password'));
            }catch(PDOException $e){
                die($e->getMessage());

            }
        }


        public static function getInstance()
        {
            if(!isset(self::$_instance)){
                self::$_instance = new DB();
            }

            return self::$_instance;
        }


    }



    ?>

index.php index.php

    <?php
       require_once 'core/init.php';
       DB::getInstance();
    ?>

It seems like your paths for autoloading your classes is wrong, please try the following: 自动加载类的路径似乎不正确,请尝试以下操作:

spl_autoload_register(function($class)
   {

require_once '/../classes/' . $class . '.php';
 }
    )

or please use an absolute path when requiring files, this will always ensure that your files will load. 或在需要文件时使用绝对路径,这将始终确保文件将被加载。

spl_autoload_register(function($class)
   {

require_once __DIR__ .'/classes/' . $class . '.php';
 }
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM