在上一个关于构建数据库类的问题中,我被告知我应该为我的静态db类切换到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);
}
}
答案 0 :(得分:3)
尝试将getConnection代码更改为:
self::$connection = new PDO("mysql:dbname=".__DB_NAME__.";host=".__DB_HOST__, __DB_USERNAME__, __DB_PASSWORD__ );