php __construct这有什么问题

时间:2014-08-27 09:17:22

标签: php pdo constructor

我的代码出了什么问题:

class Database
{
private $db;
public function __construct() 
{
$dbname = 'dbname';
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';

$connStr = "mysql:$dbhost; dbname=$dbname";
try
{
    $this->db = new PDO($connStr, $dbuser, $dbpass);
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} 
catch (Exception $ex) 
{
    echo $ex->getMessage();
    exit;
}   
}

public function getTableFromSQLQuery($query, $params)
{
$db = $this->db;
$result = $this->db->prepare($query);
if (isset($params) && count($params)>0)
    foreach($params as $key=>$param)
    $result->bindParam ($key, $param);
$result->execute();
return $result->fetchAll(PDO::FETCH_ASSOC);
}

}

并从代码中调用它:

$db = new Database();
$query = "SELECT * FROM mytable";   
$rowsCategories = $db->getTableFromSQLQuery($query, null);  

错误:致命错误:未捕获异常'PDOException',消息'SQLSTATE [3D000]:无效的目录名称:1046未选择数据库'
调试器中的问题在类数据库中丢失$ db,为什么?如果我每次都使用$ db = new PDO(所有参数)它可以工作,但如果我使用构造函数 - 它不会。帮助,谢谢

2 个答案:

答案 0 :(得分:5)

连接字符串应为

$connStr = "mysql:host=$dbhost;dbname=$dbname";

答案 1 :(得分:0)

$connStr更改为:

$connStr = "mysql:host=". $dbhost .";dbname=". $dbname;