我是编程新手,想使用PDO类连接到ms-access(accdb)数据库.
Environement:PHP(5.5.11)/ XAMPP / Windows 7专业版.启用了ODBC(win32)的PDO驱动程序.
class db{
protected $dbName = "C:\xampp\htdocs\BillboardsManagement\Core\config\Billboards.accdb";
protected $Uid="";
protected $Upass="";
protected $conn;
public function __construct() {
try{
$this -> conn = new PDO('odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=$this->$dbName;Uid=$this->$Uid;Pwd=$this->$Upass');
} catch (Exception $e) {
echo "\n $e-> getMessage()\n";
}
}
}
当我尝试实例化该类时,我收到以下错误:
exception ‘PDOException’ with message ‘SQLSTATE[IM002]
SQLDriverConnect: 0 [Microsoft][ODBC Driver Manager] Data source name
not found and no default driver specified’ in
C:\xampp\htdocs\BillboardsManagement\Core\config\config.php:13 Stack
trace: #0
C:\xampp\htdocs\BillboardsManagement\Core\config\config.php(13):
PDO->__construct(‘odbc:DRIVER={Mi…’) #1
C:\xampp\htdocs\BillboardsManagement\Views\selectBB.php(3):
db->__construct() #2 {main}-> getMessage() Fatal error: Call to a
member function prepare() on a non-object in
C:\xampp\htdocs\BillboardsManagement\Core\classes\bbClasses.php on
line 11
在此先感谢您的帮助.
更新:我知道之前已经回答了类似的问题.但我正处于学习过程中.上一篇文章的答案是使用adodb而不是PDO(出于我完全同意的原因),但我仍然对我在特定情况下出了什么问题感到好奇.我仍然无法确定我的代码是否有问题,或者是某些odbc驱动程序或配置问题.
解决方法:
您在此字符串中提供连接详细信息:
'odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=$this->$dbName;Uid=$this->$Uid;Pwd=$this->$Upass'
如果我们检查how strings work in PHP,我们可以阅读关于我们的单引号字符串:
Unlike the double-quoted and heredoc syntaxes, variables and escape
sequences for special characters will not be expanded when they occur
in single quoted strings.
所以PHP会尝试打开一个名为$this-> $dbName的文件.因此,首先,您可能需要其中一种语法:
>双引号字符串:“文件名$foo blah”
>连接:’文件名’. $foo. ‘blah’
现在,您想要从对象属性中读取文件名:
protected $dbName = "C:\xampp\htdocs\BillboardsManagement\Core\config\Billboards.accdb";
manual explains的语法是:
$this->dbName
但是,你有这个:
$this->$dbName
一旦解决了这个问题,验证变量是否包含您认为的变量总是一个好主意.为此,我推荐var_dump():
$connection_string = 'odbc:DRIVER={Microsoft ....';
var_dump($connection_string);
值得注意的是,我所解释的所有内容都与基本的PHP语法有关.到目前为止,PDO和Access问题都没有出现.它总是有助于隔离您的问题.