PDO:为什么这会导致错误?

时间:2012-09-01 00:20:03

标签: php pdo

我不明白为什么在创建这样的对象时出现此错误:

错误在此行的index.php中:

$dbPerfiles = new DB_Functions();

错误是这样的:

PDO Connection error: invalid data source name

的config.php

<?php
define ("DB_USER","root");
define ("DB_PASS","root");
define ("DNS","mysql:host=localhost;dbname=example");
?>

DB_Connect.php

<?php
require_once 'config.php';
class DB_Connect {
    private static $_instance;

    //Connecting to database
    public function &pdo_connect() {    
        if(!self::$_instance) {
            try{
                self::$_instance = new PDO(DNS,DB_USER, DB_PASS);
                self::$_instance->setAttribute(PDO::ATTR_PERSISTENT, true);
                self::$_instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $ex) {
                die("PDO Connection error: ".$ex->getMessage()."<br/>");
            }
        }
        return self::$_instance;
    }

    private function __construct() {
    }

    private function __clone() {
    }
}
?>

DB_Functions.php

<?php
    session_start();
    require_once 'DB_Connect.php';

    class DB_Functions extends DB_Connect{

        private $dbConnect = "";

        public function __construct() {
            $this->dbConnect = $this->pdo_connect();
        }

        public function __destruct() {
            $this->dbConnect = null;
        }

        public function getDetails() {
            try {
                //sql statement

            } catch (PDOException $e) {
                echo "Error: ".$e->getMessage()."<br/>";
                return false;
            }
        }
    }
?>

的index.php

<?php 
session_start();
$max_time = 1800;
$current = time();
if(!isset($_SESSION['clientmac']['un']) ) { 
    $_SESSION['clientmac']['un'] == "";
    header('Location: index.php');
} else {
    if (!isset($_SESSION['timeLogin'])){
        $_SESSION['clientmac']['tl'] = time();
    } else {
        $session_life = $current - $_SESSION['clientmac']['tl'];    

        if ($session_life > $max_time) {
            header('Location: include/logout.php');
        } else {
            $_SESSION['clientmac']['tl'] = time();
        }
    }

    require_once 'include/DB_Functions.php';
    $dbPerfiles = new DB_Functions();  //With this line shows the error

    //code to connect to getDetails() function in DB_Functions.php and
    //retrieve some data.

?>
<!doctype html>
<html lang=en>
<!--
CODE HTML
-->
</html>
<?php
}
?>

我想连接到DB_Functions并连接getDetails()函数或其他函数 在这个文件中并检索数据..只有那个!

我希望我已经解释过了。

此致!!

2 个答案:

答案 0 :(得分:1)

无效的数据源名称等错误可以参考:

  1. DSN语法不正确(在您的情况下看起来是正确的);
  2. DSN参数不正确
    1. 主机可能不是localhost(你的mysql配置可能不允许通过TCP或localhost自身连接,但我对此表示怀疑,因为允许来自localhost的TCP连接是默认的);
    2. 数据库名称可能不正确(因为在您的代码中为example)让我觉得您可能没有创建名为example的数据库;

答案 1 :(得分:1)

解决了!只有我必须添加这一行

require_once 'include/config.php'; 

上面

require_once 'include/DB_Functions.php'; 

并且有效,但我不明白为什么?

因为在DB_Connect.php中这一行是相同的。