【发布时间】:2014-02-12 02:46:10
【问题描述】:
我正在开发一个需要从外部 MSSQL 数据库获取数据的应用程序。我花了很多时间尝试使用 PHP 连接到 MSSQL 的各种方法,但有几条路线已被贬值。
在我运行 Debian 的生产环境中,我能够通过以下方式与 PDO_DLIB 和 FreeTDS 建立连接:
$this->db = new \PDO('dblib:host='.$thedb_host_prod.';dbname='.$thedb_database_name_prod, $thedb_database_user, $thedb_database_pass);
在 Windows 上,MSSQL 已折旧。我相信我使用的是 Microsoft SQL Server 驱动程序,并且只能让它与 ODBC 一起使用,它看起来像这样:
$dsn = "Driver={SQL Server};Server=".$thedb_host_dev.";Database=".$thedb_database_name_dev;
$this->odbc = odbc_connect($dsn, $thedb_database_user, $thedb_database_pass);
然后,问题就变成了,在每种方法中,我需要为 ODBC 做一些不同于为 DLIB 做的事情。
public function exampleMethod(){
// logic and create the query in $query
if($this->dev == false){
// PRODUCTION
try {
$stmt = $this->db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
} else {
// DEVELOPMENT
$query = $query;
$stmt = odbc_exec($this->odbc, ($query));
$result = array();
while($currentRow = odbc_fetch_object( $stmt )){
$jobNumber = $currentRow->Code; // Set object key to jobNumber
array_push($result, $currentRow);
}
}
}
这确实有效,但问题是,需要如何准备 ODBC 查询与应如何准备 DBLIB 查询,这意味着如果我不想在每种方法中编写两次查询,我有在每个动作之前创建它。这真的很糟糕,因为这意味着我没有使用 PDO 的 bindValue 将变量放入查询中。
那么,有没有人能够在 Windows 环境中使用 PHP 5.4 和 MSSQL 进行 PDO 工作?有没有人看到一种保护查询的方法,不会让我在每种方法中重复查询,一次用于 ODBC,一次用于 DBLIB?
我目前的计划是开发应用程序,然后删除所有 ODBC 内容,这将使我能够正确地将查询放入 $stmt 中,避免这个问题。但在那之前,它让开发成为一个巨大的痛苦。
【问题讨论】:
标签: php sql sql-server windows pdo