-1

在上一个关于构建数据库类的问题中,我被告知我应该为我的静态数据库类切换到 PDO

到目前为止,这就是我所拥有的一切,除了 dbDataArray 打印出一个空数组,即使我知道表中有数据也是如此。

class db
{
    private static $connection;
    const __DB__HOST__      = __DB__HOST__;
    const __DB_USERNAME__   = __DB_USERNAME__;
    const __DB_PASSWORD__   = __DB_PASSWORD__;
    const __DB_NAME__       = __DB_NAME__;

    private static function getConnection() {
            if (self::$connection === null) {
                try {
                self::$connection = new PDO("mysql:__DB_NAME__=pdo;host=".__DB_HOST__, __DB_USERNAME__, __DB_PASSWORD__ );
                return self::$connection;
            }
            catch(PDOException $e)
            {
                echo $e->getMessage();
            }

        }
        /*** close the database connection ***/
        //self::$connection = null;
    }

    //return all results from sqlquery in array
    public static function dbDataArray($sql_string){
        $conn = self::getConnection();
        $sth = $conn->prepare($sql_string);
        $sth->execute();
        $result = $sth->fetchAll();
        print_r($result);
    }
}
4

1 回答 1

3

尝试将您的 getConnection 代码更改为:

self::$connection = new PDO("mysql:dbname=".__DB_NAME__.";host=".__DB_HOST__, __DB_USERNAME__, __DB_PASSWORD__ );
于 2013-09-19T04:23:48.180 回答